SetTimeout and setInterval

 SetTimeout and setInterval


The setTimeout and setInterval functions are used to execute code after a certain delay or at fixed intervals, respectively.



setTimeout(() => {

  console.log('Delayed execution');

}, 2000);

// Output (after 2 seconds): Delayed execution


let counter = 0;

const intervalId = setInterval(() => {

  counter++;

  console.log(counter);

  if (counter === 5) {

    clearInterval(intervalId);

  }

}, 1000);

// Output (every 1 second): 1, 2, 3, 4, 5

In the example above, setTimeout is used to execute a function after a delay of 2000 milliseconds. setInterval is used to repeatedly execute a function every 1000 milliseconds until the condition counter === 5 is met. The interval is cleared using clearInterval when the condition is satisfied.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...