以固定的时间间隔运行JavaScript函数

Dea*_*ors 29 javascript

我目前正在建立一个托管软件的网站.我想要的是添加到项目页面的是一个循环截图的幻灯片,每5秒更换一次图像.是否有任何方法可以使用JavaScript在一个时间间隔触发脚本?..或者我将不得不采用其他方法来实现我所需的功能.在此先感谢您的帮助!

Ry-*_*Ry- 47

setInterval:

function doSomething() {
    alert('This pops up every 5 seconds and is annoying!');
}

setInterval(doSomething, 5000); // Time in milliseconds
Run Code Online (Sandbox Code Playgroud)

每隔n毫秒重复一次你想要调用的函数.(setTimeout顺便说一下,会调用一个超时的函数.)

如果您想要停止计时器,请保持setInterval返回值并将其传递给clearInterval.


And*_*gee 16

你想要这个setInterval功能.

setInterval(function() {
  // This will be executed every 5 seconds
}, 5000); // 5000 milliseconds
Run Code Online (Sandbox Code Playgroud)

基本参考:http://www.w3schools.com/jsref/met_win_setinterval.asp(请忽略对"lang"参数的引用)

更深入的参考:https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval

  • [顺便说一句,W3Schools不是最好的参考](http://w3fools.com) (3认同)