setTimeout 和clearTimeout 的混淆
我有一个按钮,可以在 div 翻过来时更改其背景。背景需要在计时器上更改,因此我使用 setTimout 来执行更改背景的方法。我认为clearTimeout会取消并且我已经设置了超时,所以我把它放在mouseleave事件上。然而,它似乎并没有停止超时。我的逻辑对吗?
$("#h2Buzz").mouseenter(function () {
setTimeout(playV(), 2700);
setTimeout(playP(), 5400);
});
$("#h2Buzz").mouseleave(function () {
clearTimeout(playV());
clearTimeout(playP());
});
function playV() {
$("#ServicesBackgroundImage2").css("background-image", "url(/images/v.jpg)");
}
function playPn() {
$("#ServicesBackgroundImage2").css("background-image", "url(/images/p.jpg)");
}
I have a button that changes the background of a div when its rolled over. the background needs to change on a timer so i have used setTimout to execute methods that change the backgrounds. I thought clearTimeout would cancel and timeouts i have set so i put this on the mouseleave event. However it doesnt seem to stop the timeouts. Is my logic right here?
$("#h2Buzz").mouseenter(function () {
setTimeout(playV(), 2700);
setTimeout(playP(), 5400);
});
$("#h2Buzz").mouseleave(function () {
clearTimeout(playV());
clearTimeout(playP());
});
function playV() {
$("#ServicesBackgroundImage2").css("background-image", "url(/images/v.jpg)");
}
function playPn() {
$("#ServicesBackgroundImage2").css("background-image", "url(/images/p.jpg)");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您错误地使用了
setTimeout
和clearTimeout
。setTimeout
函数返回超时的句柄,该句柄将被传递到clearTimeout
中以停止超时。另请注意,
setTimeout(playV(), 2700);
将立即调用playV()
并在 2.7 秒后执行其返回值。您应该传递一个函数对象playV
来代替。You are using
setTimeout
andclearTimeout
wrongly. ThesetTimeout
function returns a handle to the timeout, which is to be passed intoclearTimeout
to stop it.Also note that
setTimeout(playV(), 2700);
will callplayV()
now and execute its return value 2.7 seconds later. You should pass a function objectplayV
in instead.为您的
setTimeout
分配一个变量,然后将其传递给clearTimeout
来清除它,即(注意我在您的第一个
setTimeout
参数周围添加了引号)Assign a variable to your
setTimeout
, which you then pass toclearTimeout
to clear it, i.e.(Note I added quotes around your first
setTimeout
argument)当您调用
setTimeout
时,它会返回一个数值。您应该存储该值,因为这是clearTimeout 所需要的。因此,请跟踪两个 setTimeout 的返回值(它们会不同)。并在您可以从这两个函数访问的范围内跟踪它们。快速“n”肮脏示例:
此外,您使用“playV()”调用 setTimeout,这是不正确的,因为它将立即以这种方式调用该函数。您可以将括号留在后面,因此只需
setTimeout( playV, 3500 );
When you call
setTimeout
, it returns a numeric value. You should store this value, because this is what you need for clearTimeout. So keep track of the return value from both setTimeout's (they will be different). And keep track of them in a scope you can access from both functions.Quick 'n' Dirty Example:
Also, you are calling setTimeout with 'playV()', this is incorrect as it will immediately call that function this way. You can leave the brackets behind, so just
setTimeout( playV, 3500 );