timer print message in javascript

There are two ways to print a message after a certain time delay in JavaScript:

  1. Using setTimeout():
index.tsx
setTimeout(function(){
  console.log("Delayed message after 5 seconds");
}, 5000); // 5 seconds delay
102 chars
4 lines
  1. Using setInterval():
index.tsx
let count = 0;
let interval = setInterval(function(){
  if(count === 5) {
    clearInterval(interval); // stop the interval after 5 iterations
  } else {
    count++;
    console.log("Repeated message after every 1 second");
  }
}, 1000); // 1 second delay
257 chars
10 lines

In the first method, setTimeout() is used to execute a function after a certain time delay specified in milliseconds.

In the second method, setInterval() is used to execute a function repeatedly after a certain time delay specified in milliseconds. The interval function keeps track of the number of iterations and stops after the desired number of iterations is reached.

gistlibby LogSnag