0

I'm trying to loop a function with a setInterval and then, when a condition is hitted:

  1. Pause the setInterval loop
  2. Call and execute an async function
  3. Resume the setInterval loop

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
Marco
  • 161
  • 8

1 Answers1

-1

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);

Raphael PICCOLO
  • 2,095
  • 1
  • 12
  • 18