setTimeout()
clearTimeout()
setInterval()
clearInterval()

In javascript the timer functions are already built in for you: setTimeout(), clearTimeout(), setInterval(), clearInterval(). Timers can be a little strange in Javascript at first, due to Javascript’s single-threaded/asyncronous nature. I’ll show you what i mean:


// what will be called first, the anonymous function passed into
// setTimeout or the console.log() that occurs after the setTimeout?

setTimeout(function() {
  console.log('from inside the setTimeout method!')
}, 2000)

console.log('after the setTimeout method')

// => 'after the setTimeout method'
// => 'from inside the setTimeout method!'

If your new to Javascript, you may be confused why the console.log() after the setTimeout get called BEFORE the console.log() within the setTimeout. It does this because Javascript is asyncronous. This means that the program will try to run from start to finish as quickly as possible, and if a statement(s) takes time to complete, you tell it what to do once the process is done ( called a callback ) and the program continue with its’ execution without waiting for the callback.

setTimeout(func, milliseconds)

setTimeout() calls a function (can be an anonymous function) after a specified number of milliseconds. Only called ONCE.


var delayed = function() {
  console.log('i should be called after 3 seconds')
}

setTimeout(delayed, 3000)

console.log('after the timeout')

// => 'after the timeout'
// => 'i should be called after 3 seconds' called after 3 seconds

If you were to use an anonymous function it would look like the example used in the intoduction.

clearTimeout(id)

clearTimeout stops/clears a timer set using setTimeout. It is a good idea whenever you use either setTimeout or setInterval to assign it to a variable( global scope pref ), so when you call clearWhatever you can pass in the name of the variable for the timer.

For example, image you have some HTML buttons with click handlers to call an alert in X seconds, and another button to cancel it before the alert happens.


var timeoutID;

function delayedAlert() {
  timeoutID = setTimeout(slowAlert, 2000);
}

function slowAlert() {
  alert("That was really slow!");
}

function clearAlert() {
  clearTimeout(timeoutID);
}

setInterval(func, milliseconds)

setInterval() calls a function every specified number of milliseconds similar to setTimeout(), but instead of calling the function once, it will repeatedly call it until clearInterval() is called. Here is a small program that will spin up 3 seperate setIntervals()’s, one for each person, and give a shoutout 5 times for each person, and then stop:

var ppl = [
  { name: 'frank', age: 20 },
  { name: 'paul', age: 222 },
  { name: 'susan', age: 63 }
]

function theInt(person) {
  var i = 0;
  setInterval(() => {
    if (i === 5) {
      clearInterval(theInt)
    } else {
      i++
      console.log(`can i get a shoutout for my boi ${person.name} for the ${i} time?`)
    }
  }, 500)
}

for (var i = 0; i < ppl.length; i++) {
  var person = ppl[i];
  theInt(person)
}

// => can i get a shoutout for my boi frank for the 1 time?
// => can i get a shoutout for my boi paul for the 1 time?
// => can i get a shoutout for my boi susan for the 1 time?
// => can i get a shoutout for my boi frank for the 2 time?
// => can i get a shoutout for my boi paul for the 2 time?
// => can i get a shoutout for my boi susan for the 2 time?
// ...
// ...

clearInterval(id)

clearInterval() is called to clear a setInterval() from memory. In the example above, we are saying if the ‘i’ variable for each is equal to 5, call clearInterval(theInt), which is the name of the function. We are using recursion here to call clearInterval() on on the method the clearInterval() is being called inside of.