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");
}
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");
}
Share
Improve this question
edited Jul 21, 2019 at 15:43
Brian Tompsett - 汤莱恩
5,88372 gold badges61 silver badges133 bronze badges
asked Dec 12, 2009 at 14:04
RichRich
2092 gold badges4 silver badges6 bronze badges
3 Answers
Reset to default 19You 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);