I'm trying to loop a function with a setInterval and then, when a condition is hitted:
What's the best way to do it in Javascript? I have something like this:
var refreshId = setInterval(Myfunction, 5);
function Myfunction(){
---do something---
if (conditionIsHitted){
externalFunction();}
}
---resume the setInterval loop again
you cant "pause" a setinterval. nor a setTimeout. but you can stop it and start it again later. like start with a 10 sec timeout. stop it 2 seconds later. and restart it later with a 8 sec timeout.
// run something after 10 sec - will never actually be runned, because stopped later
let timeout = setTimeout(function() {
console.log('10 sec elapsed');
}, 10000);
// stop after 2 seconds and relaunch the work to be done
setTimeout(function() {
clearTimeout(timeout);
setTimeout(function() {
console.log('10 sec elapsed');
}, 8000);
}, 2000);