JavaScript中的循环计时器 [英] Loop timer in JavaScript

查看:115
本文介绍了JavaScript中的循环计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一段JavaScript代码,比如每2000毫秒。

  setTimeout('moveItem()', 2000)

以上将在2000毫秒后执行一个函数,但不会再执行它。 / p>

所以在我的moveItem函数中我有:

  function moveItem() {
jQuery(。stripTransmitter ul li a)。trigger('click');
setInterval('moverItem()',2000);
}

这不起作用,因为我想执行触发器点击jQuery一段代码每个间隔为2000毫秒,但现在它一直被调用,脚本需要被中断。除此之外,我觉得这是非常差的质量编码......你们怎么解决这个问题?

解决方案

注意 setTimeout setInterval 是非常不同的函数:




  • setTimeout 将在超时后执行代码

  • setInterval 将以提供的超时间隔执行代码 forever



两个函数都返回计时器ID ,您可以使用它来中止超时。您所要做的就是将该值存储在变量中并将其用作 clearTimeout(tid) clearInterval(tid)



因此,根据您的目的,您有两个有效的选择:

  //设置超时
var tid = setTimeout(mycode,2000);
函数mycode(){
//做一些事情......
tid = setTimeout(mycode,2000); //重复自己
}
函数abortTimer(){//当你想要停止计时器时调用
clearTimeout(tid);
}

  //设置区间
var tid = setInterval(mycode,2000);
函数mycode(){
//做一些东西......
//无需回忆函数(这是一个间隔,它会永远循环)
}
函数abortTimer(){//当你想要停止计时器时调用
clearInterval(tid);
}

这两种方法都是非常常见的方法。


I need to execute a piece of JavaScript code say, each 2000 milliseconds.

setTimeout('moveItem()',2000)

The above will execute a function after 2000 milliseconds, but won't execute it again.

So inside my moveItem function I have:

function moveItem() {
    jQuery(".stripTransmitter ul li a").trigger('click');
    setInterval('moverItem()',2000);
}

This does not work because I want to execute the trigger click jQuery piece of code each interval of 2000 milliseconds, but right now it is being called all the time and the script needs to be interrupted. Besides that, I feel this is very bad quality coding... How would you guys solve this?

解决方案

Note that setTimeout and setInterval are very different functions:

  • setTimeout will execute the code once, after the timeout.
  • setInterval will execute the code forever, in intervals of the provided timeout.

Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as argument to clearTimeout(tid) or clearInterval(tid) respectively.

So, depending on what you want to do, you have two valid choices:

// set timeout
var tid = setTimeout(mycode, 2000);
function mycode() {
  // do some stuff...
  tid = setTimeout(mycode, 2000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
  clearTimeout(tid);
}

or

// set interval
var tid = setInterval(mycode, 2000);
function mycode() {
  // do some stuff...
  // no need to recall the function (it's an interval, it'll loop forever)
}
function abortTimer() { // to be called when you want to stop the timer
  clearInterval(tid);
}

Both are very common ways of achieving the same.

这篇关于JavaScript中的循环计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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