I have the following code but the clear timeout doesn't work and I can't understand why, does anyone have any ideas? (Using the Prototype framework)
function foo() {
$("navigation").observe('mouseover',
function (event) {
clearTimeout(bar);
}
).observe('mouseout',
function (event) {
setTimeout(bar, 1000);
}
);
}
function bar() {
alert("hi");
}
To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.
clearTimeout() inside setTimeout() method not working in JSIt does "work", but your logic is incorrect. After you called clearTimeout you are calling setTimeout again. Instead of calling clearTimeout you should just exit the function.
This will be the ID that was returned by the setTimeout() function. You can clear the timeout by using this id which identifies the timeout. The ids which will be sent as a parameter to this function are being shared by two functions setTimeout() and setInterval().
Clearing setTimeout What is this? To clear or cancel a timer, you call the clearTimeout(); method, passing in the timer object that you created into clearTimeout(). For example, the code below shows how to properly clear a timer inside of a functional React component.
You need to store the result of setTimeout
in a variable, and use clearTimeout
to clear that 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");
}
Because the clearTimeout
function take the argument returned by the setTimeout
function:
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");
}
See the mozilla docs on window.setTimeout():
setTimeout actually returns a reference which you can use to clear the timeout:
tId = setTimeout(bar, 1000);
clearTimeout(tId);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With