Search code examples
javascriptjquerysettimeoutleafletcleartimeout

leaflet javascript - how to clearTimeout a setTimeout on a marker?


I am adding markers like this to my map:

 map.addLayer(l), setTimeout(function() {
      map.removeLayer(l)
 }, 1e4),

which removes after 10 seconds each marker again. Now I would like to achieve that when the user clicks during those 10 seconds on a marker that the market stays visible on the map. So far I have:

l.on('click', function(e) {

console.log(e);
console.log(e.layer._leaflet_id);
console.log(l);

clearTimeout(e.layer._leaflet_id);

});

But it does now work. Any idea how I can achieve this?


Solution

  • You need to cancel the setTimeout by calling the clearTimeout using the relevant ID.

        var myVar;
        timeout_init();
    
        function timeout_init() {
            myVar = setTimeout(function(){
                $('.marker').hide();
                },5000);
        }
    
    $( ".marker" ).click(function() {
        clearTimeout(myVar);
    });
    

    See example Fiddle