Last Updated: February 25, 2016
· bhousman

A situation where you should avoid setInterval.

Example function used for Approach 1 and Approach 2 below:

// Outputs "Hi" in the console when called
function sayHi() {

Approach 1: Bad method of accomplishing this

This approach is considered bad practice as sayHi() function will be called every 5 seconds regardless of whether or not it has finished executing from the previous times it was called. This can become particularly problematic when you're dealing with AJAX requests as it has to fetch or push data over the network and response times are variable and unknown.

// Will call sayHi() function every 5 seconds
setInterval(sayHi, 5000);

Approach 2: Preferred method of doing this

This is the preferred approach as it will wait for sayHi() function to finish executing before it is called again. In this case you're waiting 5 seconds after executing, not executing every 5 seconds.

// Self-executing function that uses setTimeout instead of setInterval
! function betterApproach() { 
  setTimeout(sayHi, 5000);

// The self-executing function wrapper can also be written like this:
(function betterApproach() { 
  setTimeout(sayHi, 5000);