I'm wondering how to loop a script every x seconds. I'm relatively new to javascript and jquery, however I do know how to use some of it in HTML.
I'm trying to make this script run every 34 seconds, however I don't know how to loop it as such.
Here's my script:
function byId(id){
return document.getElementById(id)
}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt) {
setTimeout(function() {
byId('audioID').play()
}, 13000);
}
However I don't know how I would loop this every 34 seconds, after it starts at 13 seconds.
Thanks!
setTimeout
makes the script run after x
miliseconds, if you want to run the script multiple times, you need to use setInterval
instead.
setInterval( function(){ byId('audioID').play() }, 34000 );
If I understand correctly, you want to start the interval after 34 seconds, so you need to do this instead:
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);
Create a new function who will execute byId('audioID').play()
every 34Secs
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt) {}
function byId(id) {
console.log(id);
return document.getElementById(id);
}
const loopTime = 34000; //34000 ms = 34secs
var startProcess = function() {
setInterval(function() {
byId('audioID').play();
}, loopTime);
};
setTimeout(startProcess, 13000);
This works. If you need to stop the interval just call clearInterval(interval)
.
var interval; setTimeout(function(){ console.log("Started interval after 1 sec"); interval = setInterval(function(){ console.log("hai")},2000) },1000);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.