Languages

JavaScript - how to setInterval specified amount of times?

3 points
Asked by:
Dirask Community
6900

Can you tell me how to call setInterval method only specified number of times?

2 answers
12 points
Answered by:
Dirask Community
6900

I found the solution:

Just wrap the code inside setInterval with if statement:

// ONLINE-RUNNER:browser;

let x = 0;
let interval = setInterval(() => {
  console.log(x);
  if (++x === 3) {
    clearInterval(interval);
  }
}, 1000);

Note:

For more information and runnable examples go to the - JavaScript - setInterval example.

0 comments Add comment
10 points
Answered by:
Dirask Community
6900

setTimeout is useful to do it.

// ONLINE-RUNNER:browser;

let x = 0;
const action = () => {
  console.log(x);
  if (++x < 3) {
    setTimeout(action, 1000);
  }
};
setTimeout(action, 1000);

Check the following resources:

  1. JavaScript - how to make async loop class with next iteration confirmation?
  2. JavaScript - how to make async loop that continues iteration when is ready in modern js?
  3. JavaScript - how to make buffered async loop class with next iteration confirmation?
0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join