Understanding setInterval() & setTimeout()

feat. A Slot Machine Game

Zoe Kirsh
5 min readFeb 1, 2021

This blog will give you the low down on JavaScript’s built-in setInterval() and setTimeout() functions, and describe how we used setTimeout() to create the rolling numbers effect in a game styled after a slot machine.

setInterval() and setTimeout()

Both of these are supremely useful JavaScript built-ins. setTimeout() is easy to remember because the name is rather self-explanatory: you pass it a function and an amount of time, and it will start the timer, wait until it times out, then execute the function (only once). setInterval() is also aptly named. You pass it the same arguments: a function and a time; and it will execute that function on the interval of your desired time. More plainly, it will wait <time> milliseconds, run the function, wait <time> milliseconds, run the function again, and continue over and over like that forever. Luckily it has a sister, clearInterval() which you can use to stop setInterval().

setTimeout() is great when:

  • you want an action to occur at (or after) a certain time
  • you want to call multiple functions, but you need to have some wait time between their executions

setInterval() is great when:

  • you want something to happen over and over (a timer that increments, or a countdown that decrements, or a fetch request for updates, etc.)

One crucial thing to note is that the return value of setInterval() is an id number that refers to the interval function itself. This is so that when you want to remove or stop the interval later, you can pass the unique identifier to clearInterval(). It seems that best practice is to set the interval function to a variable, like so:

so that you can simply pass the variable to clearInterval() to make it stop, like so:

(continuing the example from above)

Let’s look at an example that utilizes both setInterval() and setTimeout(). Say we would like to have a timer running on the page, but we want the timer to stop after thirty seconds. We can use setInterval() to create a counting function that will continually increase a counter displayed on the page every second. Then we can use setTimeout() to wait for 30 seconds, and use clearInterval() to stop the interval. Check out the snippet below:

There is one caveat here that could throw off beginners. Notice how in the codepen snippet, we wrap clearInterval() in a function called stop(), and pass stop to setTimeout() rather than directly passing in clearInterval(timerId). This is because the function passed to Timeout must be a reference or pointer to clearInterval(), otherwise it will run immediately on page load as your machine is reading setTimeout(), and your interval will never execute in the first place! Wrapping clearInterval() in an anonymous function works too, as we will see in a moment.

Now that we have a basic understanding of how these functions work, allow me to demonstrate a real use case.

How I used setTimeout() to make a simple slot machine effect

A click event on the ROLL button triggers the masterRoll function.

First, a little background. We wanted to invoke the feeling of playing a slot machine, where all three numbers have a kind of rolling effect, and land on their final value at staggered times. We also wanted to keep things as simple as possible, and avoid using hundreds of lines of CSS to achieve our goal. We ended up with a strategy where each number is rolled individually by a function rollDiv() (see second image below). Inside rollDiv() is a recursive timeout function. The rollDiv that sets off the first (left-most) value in the slot machine is passed a base case of 250 milliseconds. The second is passed a base case of 300, and the last is passed 350. All three rollDiv functions are wrapped in one master function, masterRoll(), so that they are invoked at the same time. The increasing base cases mean that the first rollDiv will finish executing first, the second will finish after that, and the third after that. This creates the staggered rolling effect, even though they all start at the same time. We ensured that the final resting numbers would not be repetitive by starting each roll on a randomly generated number.

To the left you can see masterRoll(). It contains all three rollDivs, followed by a function called rollBtnTimer() whose purpose is to make the user unable to click ROLL again until the third rollDiv() is finished executing. Finally, the last piece in the master roll function is another timeout function, that waits until the last rollDiv() finishes executing, and then and only then updates the score shown at the top of the slot machine.

Essentially, rollDiv is running through an array of the numbers 1–9, changing the text content on the DOM to reflect the next number in the array (starting back at 1 once it reaches 9) with each recursive invocation of the timeout function. It increases the length of timeout with each recursion through the line

clock+= 10

until the timeout is the same or greater than the base case we passed in (250, 300, or 350, referenced by the variable stagger) which stops it from running again. Whichever number happened to be appended to the DOM on the last update is the final value the slot rests on. This creates a percolating effect of decreasing speed. If you’d like to see this code in action, checkout the whole project, and play a game of slot machine for yourself, please visit here.

--

--