我想知道如何每 x 秒循环一次脚本。我对 javascript 和 jquery 比较陌生,但我确实知道如何在 HTML 中使用其中的一些内容。
我试图让这个脚本每 34 秒运行一次,但我不知道如何循环它。
这是我的脚本:
function byId(id){
return document.getElementById(id)
}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt) {
setTimeout(function() {
byId('audioID').play()
}, 13000);
}
但是,在 13 秒开始之后,我不知道如何每 34 秒循环一次。
谢谢!
最佳答案
setTimeout
使脚本在 x
毫秒后运行,如果您想多次运行脚本,则需要使用 setInterval
代替。
setInterval( function(){ byId('audioID').play() }, 34000 );
如果我理解正确的话,你想在 34 秒后开始间隔,所以你需要这样做:
setTimeout(function(){
//Declaring the function within this code scope just for DRY purposes
var runFn = function(){
byId('audioID').play();
}
runFn(); //runs the function once before the interval starts.
setInterval(runFn, 34 * 1000 );
}, 13 * 1000);
关于javascript - 每 x 秒循环一次脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48581750/