Words and Code

One writer’s journey from words to code.

The Final Countdown: Using JavaScript’s setInterval + clearInterval Methods

It’s a brand new year, and with that comes a renewed sense of self. Also: a rather lengthy todo list. Enter #technicaltuesdays, or my attempt at beefing up my technical chops by posting a blog post every week — specifically on Tuesdays, in case it wasn’t obvious. (Sorry, Thursday, you were a close second, but you just didn’t make the cut.)

So, what’s on the menu this week? JavaScript! New year = new me, you guys. Actually, some of my technical interviews have been a bit JavaScript-heavy, so I’ve been stepping up my curly bracket game.

In honor of the new year, I wanted to use JavaScript to create a quick “New Year’s Countdown” function. Suffice it to say, it was neither quick nor easy. But I learned about two cool timing events in JavaScript – setInterval and clearInterval – and now you can learn about them, too!

setInterval()

Okay, so what exactly was my goal with this function? I wanted to it to countdown from 10 to 1 and then print out “Happy New Year!”. JavaScript has a couple different time events, but the trick is figuring out which one works best for your purposes.

I first started off trying to use the setTimeout() method, which waits a certain amount of time before executing the function that you pass it as a parameter. I was stuck for a long time trying to figure out how to get my code to execute again after every second. I quickly realized that this method wasn’t the best tool for the job.

Luckily, one method did just the trick: setInterval(). The setInterval method executes a function that you pass in as a parameter at a deteremined interval. The interval is also a parameter, and is passed in as milliseconds. Protip: 1000 milliseconds = 1 second. A generic setInterval method might look something like setInterval(functionYouWantToRun(), 1000).

This was perfect for my countdown function, which needed to do the same thing – namely, count down from ten to zero – every one second.

Here’s what my function looked like in the first iteration:

1
2
3
4
5
6
7
8
var counter = 10;
setInterval(function(){
  console.log(counter);
  counter--
  if (counter === 0) {
    console.log("HAPPY NEW YEAR!!");
  }
}, 1000);

I first created a counter variable, which I logged to the console, and then decremented by one each time the function ran. I passed in the two parameters that setInterval requires: a function to execute (in my case, an anonymous, unnamed function), and an interval at which it should be executed (every one second). I also added a conditional to log “Happy New Year!” once the counter hit zero.

So, did it work? YES! But also, NO. This code does count down from 10, and prints out “HAPPY NEW YEAR!!” when it hits zero. But now, there was another problem: it just WOULD. NOT. STOP.

Make it stop!! Or, clearInterval()

The setInterval method is great and all, until you hit an infinite loop and your code runs forever and ever and ever and – you get the idea. This method on its own doesn’t do much more than loop by default. But, when it’s combined with its twin method clearInterval(), which – you guessed it – clears the function at a certain interval, you it can acutally be quite handy.

So, how does clearInterval work? Well, it takes just one parameter: the function that you want to clear. This is important for remember for two reasons:

  1. You have to save your setInterval method to a variable
  2. This variable must be accessible (in scope) by the clearInterval method

A clearInterval method might look something like clearInterval(func), where var func = setInterval(functionYouWantToRun(), 1000).

Here’s what the second iteration of my function looked like:

1
2
3
4
5
6
7
8
9
var counter = 10;
var newYearCountdown = setInterval(function(){
  console.log(counter);
  counter--
  if (counter === 0) {
    console.log("HAPPY NEW YEAR!!");
    clearInterval(newYearCountdown);
  }
}, 1000);

I saved my function to variable called newYearCountdown, and then passed that variable in as a parameter to my clearInterval method, which will only fire when the counter variable is set to zero. When var counter is set to zero, a couple things will happen:

  1. The string HAPPY NEW YEAR!! will be logged to the console
  2. The clearInterval method will execute
  3. The setInterval method will stop running

And this is what will be printed out:

1
2
3
4
5
6
7
8
9
10
11
10
9
8
7
6
5
4
3
2
1
HAPPY NEW YEAR!!


Maybe my next blog post should be figuring out how to change that gif from “2012” to “2015”…

Hope you had a wonderful New Year’s! Here’s to 2015 and many more Technical Tuesdays! (I hope.)

tl;dr?

  • The setInterval method takes a function to execute and a interval in milliseconds.
  • The clearInterval method takes an in-scope variable which points to the setInterval method.
  • Both of these timing events work together as a pair.
  • Want to read more about timing events in JavaScript? Check out setInterval + clearInterval’s cousins, setTimeout and clearTimeout.