How to execute a function after two second hover?

This is my current code.

google.maps.event.addListener(marker, `mouseover`, function() { alert('loaded when i hovered'); }); 

but I want the function to execute if the mouse is over the element for two seconds .

I tried this, but it did not work.

  google.maps.event.addListener(marker, `mouseover 2000`, function() { alert('loaded after then when i stay mouse 2 sec'); }); 

What do I need to do to execute the function after two second hover?

+4
source share
3 answers

You need to use a timer. Set it in mouseover, then in the timer callback do your job; also you need to handle the mouseout event where you stop the timer.

 var timeoutId = null; google.maps.event.addListener(marker, 'mouseover',function() { timeoutId = window.setTimeout(function(){ alert("I did it!"); }, 2000); } ); // Cancel your action if mouse moved out within 2 sec google.maps.event.addListener(marker, 'mouseout',function() { window.clearTimeout(timeoutId) }); 
+6
source

It will be something like this using setTimeout

 var timer; google.maps.event.addListener(marker, 'mouseover', function() { timer = window.setTimeout(function(){ alert("Stackoverflow Rocks!!!"); }, 2000); } ); google.maps.event.addListener(marker, 'mouseout', function() { window.clearTimeout(timer); } ); 
+3
source

Call setTimeout on the mouseover event. Store the return value somewhere in common (e.g. in closure).

Call clearTimeout on the mouseout event. If this event does not fire before two seconds have passed, the function you pass to setTimeout called.

0
source

Source: https://habr.com/ru/post/1440309/


All Articles