JavaScript: Timers

There are two types of timers: setTimeout and setInterval.

setTimeout()

setTimeout( () => console.log('show this after 3 seconds'), 3000);

The code will continue to be read after the setTimeout, it will run the timer in the background while it continues the code.

Timer can be cleared before executed using clearTimeout()

setInterval()

Creates a timed loop.

setInterval(function () {
  const now = new Date();
  console.log(now);
}, 1000);

Example Timer countdown

const startLogoutTimer = function() {
  const tick = function() {
    const min = String(Math.tunc(time / 60).padStart(2,0);
    const sec = String(time % 60).padStart(2,0); // remainder literal

    // In each call, print the remaining time to UI
    labelTimer.textContent = `${min}:${sec}`;

    // when - seconds, stop timer and log out user
    if(time === 0) {
      clearInterval(timer)
    }

    // Decrease by 1s
    time--;

  }

  // Set time to 5 minutes
  let time = 100;
  
  // Call the timer every second
  tick()
  const startTimer = setInterval(tick , 1000}
}

Leave a Reply

Your email address will not be published. Required fields are marked *