[英]Run JavaScript function at regular time interval
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.
我想要添加到项目页面的是一个循环播放屏幕截图的幻灯片,大约每5秒更改一次图像。 Is there any way to a script triggered at a time interval using just JavaScript?
有什么办法可以仅使用JavaScript在一定时间间隔内触发脚本吗? ..or will I have to resort to alternative methods for achieving my desired functionality.
..或者我将不得不采用替代方法来实现所需的功能。 Thanks in advance for any help!
在此先感谢您的帮助!
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 n milliseconds. 每隔n毫秒将您要重复调用的函数传递给它。 (
setTimeout
, by the way, will call a function with a timeout.) (顺便说一下,
setTimeout
将调用带有超时的函数。)
If you ever want to stop the timer, hold onto setInterval
's return value and pass it to clearInterval
. 如果您想停止计时器,请保留
setInterval
的返回值并将其传递给clearInterval
。
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
You can use window.setInterval
您可以使用
window.setInterval
Sample usage: 用法示例:
window.setInterval(function () {
console.log("foo");
}, 3000);
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);
<script>
var intervalVariable=setInterval(function(){
//Your operation goes Here
},1000); // executes every 1000 milliseconds(i.e 1 sec)
function stopTimer()
{
clearInterval(intervalVariable);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.