In this post, I’ll be discussing the setTimeout and setInterval methods in JavaScript, using the Feynman technique with the classic cartoon Scooby Doo.
This post is part of my Feynman Technique & 20 Hour Method challenge. For more info, please click here.
We know in JavaScript you can set up instructions (function) to execute after a button has been pressed or a key has been entered (addEventListener), but how about timers?. We can set automatic timers for code to execute that start counting down the second the site has loaded. It’s called the “setTimeout” method, and to assist me in explaining how it works will be the classic “Scooby-Doo Mysteries”.
setTimeout in Action:
After napping, Shaggy decides to make a Super Shaggy Sandwich. The ingredients are sardines, marshmallows, and fudge. Not my cup of tea, they’re eating it, so we’ll use it for our code.
1 const ingredients = [`sardine`, `marshmallow`, `fudge`];
2 const superShaggySandwich = setTimeout(
3 (ing1, ing2, ing3) =>
4 console.log(
5 `Like WOW, my favorite! A double-triple decker ${ing1} and ${ing2} ${ing3} sandwich!`
6 ),
7 5000,
8 ...ingredients
9 );
Let me break it down for you.
- Line 1: This is the list of ingredients that we know are in this sandwich, per Shaggy at 3:13 in the above video.
- Line 2: As we know from our previous forays in JS land, this is just the name of this set of code instructions.
- ‘setTimeout’ – The anatomy of this method includes a handler. It’s used to start the timer, but if it’s not added, then it auto starts when the page loads.
- Lines 4-6: This will execute once the time runs out.
- Line 7: the length of time before it fully executes, and finally…
- Line 8: any argument that is associated with this method.
Five seconds after our page loads, the console log comes back with this:
Like WOW, my favorite! A double-triple decker sardine and marshmallow fudge sandwich!
How Can We Prove setTimeout Worked
To ensure that the delay is not a slowdown on the load time of our browser, we add an addition to our code:
const ingredients = [`sardine`, `marshmallow`, `fudge`];
const superShaggySandwich = setTimeout(
(ing1, ing2, ing3) =>
console.log(
`Like WOW, my favorite! A double-triple decker ${ing1} and ${ing2} ${ing3} sandwich!`
),
5000,
...ingredients
);
console.log(`I'm fixing me a Super Shaggy Sandwich!`);
In the end, we added a new console log outside of the setTimeout method, which will return the following:
I'm fixing me a Super Shaggy Sandwich!
As the page loads, we see our “I’m fixing me a Super Shaggy Sandwich!” first, and then five seconds later, the superShaggySandwich code completes its execution.
I'm fixing me a Super Shaggy Sandwich!
______________________________________
Like WOW, my favorite! A double-triple decker sardine and marshmallow fudge sandwich!
This is what is called an asynchronous function. What it means is, while our “superShaggySandwich” function was working, the later console log executed completely, which is why superShaggySandwich’s console log didn’t show up until five seconds after the “I’m fixing…” line completed: the older finished after the newer.
setTimeout stopped by clear Timeout
Let’s throw a snag into this mix. For those who were fans of the old “Scooby-Doo” episodes, you know that both Shaggy and Scooby are not fans of Worcestershire sauce. If we add it to the ingredients list and add an “if” statement to the end of our code to stop them from eating the sandwich, let see what happens.
1 const ingredients = [`sardine`, `marshmallow`, `fudge`, `worcestershire`];
2 const superShaggySandwich = setTimeout(
3 (ing1, ing2, ing3) =>
4 console.log(
`Like WOW, my favorite! A double-triple decker ${ing1} and ${ing2} ${ing3} sandwich!`
5 ),
6 5000,
7 ...ingredients
8 );
9 console.log(`I'm fixing me a Super Shaggy Sandwich!`);
10
11 if (ingredients.includes(`worcestershire`)) clearTimeout(superShaggySandwich);
Here is our output, even after five seconds out:
I'm fixing me a Super Shaggy Sandwich!
Yep, it was enough to stop the boys cold.
Even though the Worcestershire sauce wasn’t called out in the argument or the console log for superShaggySandwich, it existed in the ingredients list. Our “if” statement executed the clearTimeout method, which shut down the setTimeout method in our superShaggySandwich. This is why nothing else showed up after the line 9 console log.
Let’s Talk About the setInterval Method
This method is meant to keep going at a set schedule. When you create a setInterval method, you have the handler, instructions, time between intervals, and arguments. To stop it, you’d need to set up a clearInterval method that will end the loop, but we won’t go into that here.
Knowing how much Scooby loves his snacks, we decided to set up a setInterval function that will execute the console log line ” Time for a Scooby Snack!” every three seconds. He does need time to chew them, right?
The code would look like this:
setInterval(function () {
console.log(`Time for a Scooby Snack!`);
}, 3000);
…and then every three seconds, we’d get this console log:
Time for a Scooby Snack!
…after a while, the numbers will keep piling.
40 Time for a Scooby Snack!
Since we didn’t include the clearInterval method into our function, this code will keep going farther than the Energizer Bunny or Scrappy Doo’s level of ridiculous confidence, whatever has the longest output.
…yeah, I never liked Scrappy much, either.
230 Time for a Scooby Snack!
…and it’ll keep going, and going, and going…