Home > OS >  How to maintain a specific time duration between calling two functions in JavaScript?
How to maintain a specific time duration between calling two functions in JavaScript?

Time:01-20

I want to create a code that calls one Function say toStart() and then calls another function toStop() exactly after two seconds the first function has been called until I push another button nowComplete. I have learned a function setInterval() but it only calls the function toStop() after every two seconds the page has loaded, it doesn't depend on the time when the function toStart() has started. How can I get rid of this?

<button type="button" onclick="nowend">Now Complete</button>
<script>
function toStart(){
  //do something here
  setInterval(toStop,2000);
}

function toStop(){
  //do Something here
}
function nowend(){
//Stop both the functions here to work
}

CodePudding user response:

You can do this: setTimeout() is the counterpart to setInterval().

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

sleep(2000)
  .then(() => toStart())
  .then(() => sleep(2000))
  .then(() => toStop())

With this function you are a bit more flexible.

If you want to read more about different methods you could achieve you're goal: https://www.sitepoint.com/delay-sleep-pause-wait/

CodePudding user response:

The below code will log 'started' in the console and then 'stopped' after 2 seconds. If 'nowComplete' button is pressed before 2 seconds, the timeout is cancelled and 'stopped' will not be logged. Refer setTimeout and clearTimeout

<button type="button" onclick="nowEnd">Now Complete</button>
<script>
let timeoutId;

function toStart(){
  console.log('started');
  timeoutId = setTimeout(toStop, 2000);
}

function toStop(){
  console.log('stopped');
}
function nowEnd(){
  clearTimeout(timeoutId);
}

toStart();
</script>
  • Related