JavaScript 中的循环计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2133166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:53:38  来源:igfitidea点击:

Loop timer in JavaScript

javascriptjquery

提问by Marcos Buarque

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

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

setTimeout('moveItem()',2000)

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

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

So inside my moveItem function I have:

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

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?

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

回答by Miguel Ventura

Note that setTimeoutand setIntervalare very different functions:

请注意,setTimeoutsetInterval是非常不同的功能:

  • setTimeoutwill execute the code once, after the timeout.
  • setIntervalwill execute the code forever, in intervals of the provided timeout.
  • setTimeout将在超时后执行一次代码。
  • setInterval将在提供的超时间隔内永远执行代码。

Both functions return a timer IDwhich 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.

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

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.

两者都是实现相同目标的非常常见的方法。

回答by Matt Ball

setInterval(moveItem, 2000);

is theway to execute the function moveItemevery 2 seconds. The main problem in your code is that you're calling setIntervalinside of, rather than outside of, the callback. If I understand what you're trying to do, you can use this:

是每2秒执行一次函数方式moveItem。您代码中的主要问题是您在setInterval回调内部而不是外部调用。如果我明白你想要做什么,你可以使用这个:

function moveItem() {
    jQuery('.stripTransmitter ul li a').trigger('click');
}

setInterval(moveItem, 2000);

N.B.:Don't pass strings to setTimeoutor setInterval- best practice is to pass an anonymous function or a function identifier (as I did above). Also, be careful to not mix single and double quotes. Pick one and stick with it.

注意:不要将字符串传递给setTimeoutor setInterval- 最佳做法是传递匿名函数或函数标识符(如我上面所做的那样)。另外,注意不要混用单引号和双引号。选择一个并坚持下去。

回答by Derek Adair

I believe you are looking for setInterval()

我相信你正在寻找setInterval()

回答by ntownsend

It should be:

它应该是:

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

setInterval(f, t)calls the the argument function, f, once every tmilliseconds.

setInterval(f, t)ft毫秒调用一次参数函数。

回答by Selvamani

Here the Automatic loop function with html code. I hope this may be useful for someone.

这里是带有 html 代码的自动循环功能。我希望这可能对某人有用。

<!DOCTYPE html>
<html>
<head>
<style>
div {
position: relative;
background-color: #abc;
width: 40px;
height: 40px;
float: left;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p><button id="go">Run ?</button></p>
<div class="block"></div>
<script>

function test() {
$(".block").animate({left: "+=50", opacity: 1}, 500 );
   setTimeout(mycode, 2000);
};
$( "#go" ).click(function(){
test();
});
</script>
</body>
</html>

Fiddle: DEMO

小提琴:演示

回答by Younes

You should try something like this:

你应该尝试这样的事情:

 function update(){
    i++;
    document.getElementById('tekst').innerHTML = i;
    setInterval(update(),1000);
    }

This means that you have to create a function in which you do the stuff you need to do, and make sure it will call itself with an interval you like. In your body onload call the function for the first time like this:

这意味着您必须创建一个函数,在其中执行您需要做的事情,并确保它会以您喜欢的间隔调用自己。在你的身体 onload 中,第一次像这样调用这个函数:

<body onload="update()">