Javascript 计时器算法帮助,做一次,然后 clearInterval

标签 javascript algorithm timer setinterval reset

在 mousemove 或 scroll 上我想重置一个定时器,如果它没有运行并且在定时器函数内运行一次函数。到目前为止我有这个...

var timerId,
    lastActive = new Date().getTime(),
    token;

var timerFunc = function () {

   var currentTime = new Date().getTime();
   var timeDiff = currentTime - lastActive;
   if (timeDiff > 10000) {
     //clearInterval(timerId);
   }

      //I want to do some logic here
      // but only on the first iteration of the timer
      //how can I do that?

};

$(window).on('mousemove scroll', function (e) {
lastActive = new Date().getTime();

 //only restart the timer if its not currently running. How can I do that??
if(resetTimer)
       timerId = setInterval(timerFunc , 10000);            
 });

 timerId = setInterval(timerFunc , 10000);

任何 javascript 专家都可以帮我填写吗?如果我太简短,我深表歉意。我会跟进评论中的任何问题。谢谢大家提供的任何提示、链接、技巧等。干杯。 =)

最佳答案

我会为第一个间隔使用一个 bool 变量(这很简单,只需在计时器之后添加它。您在 if(resetTimer) 中也有正确的想法,只需使用计时器即可检查它是否正在运行函数在运行和停止时设置一个全局变量。

关于Javascript 计时器算法帮助,做一次,然后 clearInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11313134/

相关文章:

javascript - Canvas 和 SVG 之间犹豫不决

javascript - 使用 jQuery 从列表中按索引选择元素

r - Bin Fu 的算法实现没有给出正确的结果

python - 试图理解这段 Python 代码

iOS:如何让定时器应用程序在后台播放自定义声音?

ios - 如果在一定时间内未交互,则隐藏按钮

使用计时器的 Javascript 幻灯片放映

javascript - 无法从未定义中读取属性 "namedValues"

javascript - 错误: TypeError: undefined is not a constructor (evaluating '$browser.cookies()' )

algorithm - 网络摄像头图像实时处理