setTimeout/clearTimeout 问题 [英] setTimeout / clearTimeout problems
问题描述
我尝试在例如之后制作一个页面以转到起始页.10 秒不活动(用户未点击任何地方).其余部分我使用 jQuery,但我的测试函数中的 set/clear 是纯 javascript.
I try to make a page to go to the startpage after eg. 10sec of inactivity (user not clicking anywhere). I use jQuery for the rest but the set/clear in my test function are pure javascript.
在我的沮丧中,我最终得到了类似这个功能的东西,我希望我可以在页面上的任何点击中调用它.计时器启动正常,但不会在单击时重置.如果该函数在前 10 秒内被调用 5 次,则会出现 5 次警报...没有 clearTimeout...
In my frustation I ended up with something like this function that I hoped I could call on any click on the page. The timer starts fine, but is not reset on a click. If the function is called 5 times within the first 10 seconds, then 5 alerts will apear... no clearTimeout...
function endAndStartTimer() {
window.clearTimeout(timer);
var timer;
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
}
有人有一些代码行吗?- 在任何点击停止,重置并启动计时器.- 当定时器命中例如.10 秒做某事.
Any one got some lines of code that will do the trick? - on any click stop, reset and start the timer. - When timer hits eg. 10sec do something.
推荐答案
你需要声明 timer
outside 函数.否则,您会在每次函数调用时获得一个全新的变量.
You need to declare timer
outside the function. Otherwise, you get a brand new variable on each function invocation.
var timer;
function endAndStartTimer() {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
}
这篇关于setTimeout/clearTimeout 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!