Javascript 悬停两秒钟后如何执行函数?
这是我当前的代码Javascript 悬停两秒钟后如何执行函数?,javascript,function,google-maps,Javascript,Function,Google Maps,这是我当前的代码 google.maps.event.addListener(marker, `mouseover`, function() { alert('loaded when i hovered'); }); 但是,如果鼠标在元素上停留两秒钟,我希望执行该函数 我试过了,但没用 google.maps.event.addListener(marker, `mouseover 2000`, function() { alert('loaded after then wh
google.maps.event.addListener(marker, `mouseover`, function() {
alert('loaded when i hovered');
});
但是,如果鼠标在元素上停留两秒钟,我希望执行该函数
我试过了,但没用
google.maps.event.addListener(marker, `mouseover 2000`, function() {
alert('loaded after then when i stay mouse 2 sec');
});
在鼠标悬停两秒钟后,我需要做什么才能使函数执行?在鼠标悬停事件中调用
setTimeout
。将返回值存储在共享的位置(例如,在闭包中)
在mouseout事件中调用
clearTimeout
。如果该事件在两秒钟内未触发,则将调用传递给setTimeout
的函数。您需要使用计时器。在mouseover中设置它,然后在计时器回调中执行您的工作;此外,还需要处理停止计时器的mouseout事件
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)
});
它将是这样的,使用
请给我举个例子。谢谢
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);
} );