setTimeout / clearTimeout问题 [英] setTimeout / clearTimeout problems

查看:160
本文介绍了setTimeout / clearTimeout问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让页面在例如之后转到起始页面。 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.

推荐答案

您需要声明计时器 这个功能。否则,每个函数调用都会得到一个全新的变量。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆