setTimeout and setInterval

Run code later or repeatedly. Always keep the id so you can stop it.

JavaScript · setTimeout and setIntervalBeginner
setTimeout(() => console.log('after 2 seconds'), 2000);

let seconds = 0;
const id = setInterval(() => {
  seconds++;
  console.log(seconds);
  if (seconds === 5) {
    clearInterval(id);                    // stop the timer
  }
}, 1000);
timersetTimeoutsetIntervalclearInterval