Using clearTimeout to cancel a timeout event

I have the following code, but the clear wait time does not work, and I can not understand why, does anyone have any ideas? (Using prototype infrastructure)

function foo() { $("navigation").observe('mouseover', function (event) { clearTimeout(bar); } ).observe('mouseout', function (event) { setTimeout(bar, 1000); } ); } function bar() { alert("hi"); } 
+6
javascript prototypejs javascript-events dom-events
source share
3 answers

You need to save the result of setTimeout in a variable and use clearTimeout to clear this variable, not the function:

 var timer; function foo() { $("navigation").observe('mouseover', function (event) { clearTimeout(timer); } ).observe('mouseout', function (event) { timer = setTimeout(bar, 1000); } ); } function bar() { alert("hi"); } 
+19
source share

Because the clearTimeout function accepts the argument returned by setTimeout :

 var t = null; function foo() { $("navigation").observe('mouseover', function (event) { if (t != null) clearTimeout(t); } ).observe('mouseout', function (event) { t = setTimeout(bar, 1000); } ); } function bar() { alert("hi"); } 
+6
source share

See the mozilla docs at window.setTimeout () :

setTimeout actually returns a link that you can use to clear the timeout :

 tId = setTimeout(bar, 1000); clearTimeout(tId); 
+4
source share

All Articles