I am trying to repeat setTimeout
every 10 seconds. I know that setTimeout
by default only waits and then performs an action one time. How can I repeat the process?
setTimeout(function() { setTimeout(function() { console.log("10 seconds"); }, 10000); }, 10000);
To repeat a function indefinitely, setTimeout can be called recursively: function repeatingFunc() { console. log("It's been 5 seconds. Execute the function again."); setTimeout(repeatingFunc, 5000); } setTimeout(repeatingFunc, 5000);
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
2 Answers. Show activity on this post. setTimeout will only execute once.
To stop a setTimeout loop with JavaScript, we can call the clearTimeout function. let timeOutVar; const myFunc = (terminator = false) => { if (terminator) { clearTimeout(timeOutVar); } else { timeOutVar = setTimeout(myFunc, 1000); } }; myFunc(true); myFunc(false);
Maybe you should use setInterval()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With