定期运行 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18070659/
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
Run JavaScript function at regular time interval
提问by DeathByTensors
I am currently building a website to host software. What I want is to add to the project pages is a slideshow of screenshots cycling, changing images about every 5 seconds. Is there any way to a script triggered at a time interval using just JavaScript? ..or will I have to resort to alternative methods for achieving my desired functionality. Thanks in advance for any help!
我目前正在建立一个网站来托管软件。我想要的是添加到项目页面的是循环截图的幻灯片,大约每 5 秒更改一次图像。有没有办法只使用 JavaScript 以时间间隔触发脚本?..或者我是否必须求助于其他方法来实现我想要的功能。在此先感谢您的帮助!
回答by Ry-
function doSomething() {
alert('This pops up every 5 seconds and is annoying!');
}
setInterval(doSomething, 5000); // Time in milliseconds
Pass it the function you want called repeatedly every nmilliseconds. (setTimeout
, by the way, will call a function with a timeout.)
将您想要每n毫秒重复调用一次的函数传递给它。(setTimeout
顺便说一下,将调用一个带有超时的函数。)
If you ever want to stop the timer, hold onto setInterval
's return value and pass it to clearInterval
.
如果您想停止计时器,请保留setInterval
的返回值并将其传递给clearInterval
。
回答by Andrew Magee
You want the setInterval
function.
你想要这个setInterval
功能。
setInterval(function() {
// This will be executed every 5 seconds
}, 5000); // 5000 milliseconds
Basic reference: http://www.w3schools.com/jsref/met_win_setinterval.asp(please ignore the reference to the "lang" parameter)
基本参考:http: //www.w3schools.com/jsref/met_win_setinterval.asp(请忽略对“lang”参数的引用)
More indepth reference: https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
更深入的参考:https: //developer.mozilla.org/en-US/docs/Web/API/window.setInterval
回答by rexcfnghk
You can use window.setInterval
您可以使用 window.setInterval
Sample usage:
示例用法:
window.setInterval(function () {
console.log("foo");
}, 3000);
回答by Pradeep Kumar Das
It Changes the date time in a div and time changes frequently after 1 sec.
它更改 div 中的日期时间,并且时间在 1 秒后频繁更改。
setInterval(function(){
var date=new Date();
$('.class').html(date);
},1000);
回答by Suryaprakash Pisay
<script>
var intervalVariable=setInterval(function(){
//Your operation goes Here
},1000); // executes every 1000 milliseconds(i.e 1 sec)
function stopTimer()
{
clearInterval(intervalVariable);
}
</script>