简体   繁体   English

如何在JavaScript中设置计时器

[英]How to set a timer in javascript

I want to run the following code: 我想运行以下代码:

ajaxUpdate(10);

With a delay of 1 second between each iteration. 每次迭代之间有1秒的延迟。 How can I do this? 我怎样才能做到这一点?

var i = window.setInterval( function(){ 
          ajaxUpdate(10); 
 }, 1000 ); 

This will call ajaxUpdate every second, until such a time it is stopped. 这将每秒调用ajaxUpdate,直到停止为止。

And if you wish to stop it later: 如果您希望稍后停止它:

window.clearInterval( i ); 

If you wish to only run it once however, 如果您只想运行一次

var i = window.setTimeout( function(){ 
          ajaxUpdate(10); 
 }, 1000 ); 

Will do the trick, and if you want to stop it running before it gets around to running once 会成功的,如果您想在运行一次之前停止运行

window.clearTimeout(i); 

The "window" prefix is not strictly nessecary, but its a good idea, because you never know when somebody else might like to create something else with the same name in visible scope that behaves differently. “ window”前缀并不是严格意义上的必备名词,而是一个好主意,因为您永远不知道别人何时会在可见范围内创建其他具有相同名称的东西,而它们的行为却有所不同。

For a complete reference on this, I always find MDC Very Helpful: 有关此内容的完整参考,我总是觉得MDC非常有用:

Also, you may wish to read this article on timers by John Resig, 另外,您可能希望阅读John Resig撰写的有关计时器的文章,

您也可以使用

setTimeout(function() {ajaxUpdate(10)}, 1000);

You can use setInterval() for that. 您可以为此使用setInterval() Create an anonymous function to be called, and use the time in milliseconds: 创建一个要调用的匿名函数,并使用毫秒为单位的时间:

var myInterval = window.setInterval(function() { ajaxUpdate(10); }, 1000);

您可以使用此JavaScript Timer类。

您也可以使用jQuery计时器: http : //plugins.jquery.com/project/timers

You can use the function setTimeout(String fonc, Integer delay). 您可以使用函数setTimeout(String fonc,Integer delay)。 For example, to execute your code each second you can do : 例如,要每秒执行一次代码,您可以执行以下操作:

window.setTimout("ajaxUpate",100);

Hope i answer to your question ;) 希望我回答你的问题;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM