Hi everyone! It’s time for another exciting edition of Boring JavaScript! This week we cover the setTimeout() method. Put away your sleeping pills and let’s jump right in.
The Future is Now
What does setTimeout() do, and why should we care?
setTimeout() is used to execute a function sometime in the future. And that’s it. Let’s look at the basic syntax:
console.log('This is before the setTimeout()');
const myHandle = setTimeout(myTimeoutFunction, 3000);
console.log('This is after the setTimeout()');
function myTimeoutFunction() {
console.log('This is from *inside* the setTimeout() function');
}
Line 2 contains the setTimeout() method. It takes two arguments:
- A function. This is the function that will execute once the timeout (2nd argument) has expired. This can be an inline function, or a named function, or an arrow function, or any equation/statement/smoke signal that resolves to a function.
- The timeout. This is the amount of time that will elapsed before the function (1st argument) is executed. The value is based in milliseconds. Just in case you forgot, 1 second equals 1000 milliseconds.
In the example above, the function ‘myTimeoutFunction’ will not execute until after 3000 milliseconds have elapsed – or three seconds if you do the math.
Also notice that setTimeout() returns a value. This value is called a handle – I’ll show you what it’s for in just a minute.
JavaScript Waits for No One.
One important point to note about setTimeout() is that it is not a ‘Wait’ method. That is, you’re not telling JavaScript to stop execution (waiting) all those milliseconds then execute your function. Instead, what JavaScript will do is queue up the execution of your function within its internal execution engine, and then continue on with the next statement.
You can see that happen if you execute the code in the previous section.
thevirtuoid@boringjavascript:~$ node setTimeout
This is before the setTimeout()
This is after the setTimeout()
This is from *inside* the setTimeout() function
thevirtuoid@boringjavascript:~$:
The first two lines would print out immediately, and the third line after 3000 milliseconds. Since the setTimout() was executed between the first and second console.log() lines, *and* if setTimeout() was a “Wait”-type method, then the third line would have printed after 3000 milliseconds, then the second console.log() would have printed. As you can see, it didn’t. Therefore, setTimeout() will not halt the execution of your script while the function waits to be executed.
Stop! I Want to Get Off the Train!
Remember that variable that got returned from the setTimeout() method? Let’s review that code:
const myHandle = setTimeout(myTimeoutFunction, 3000);
The value returned from the setTimeout() method is called a handle. This handle is a pointer to the internal mechanisms used by JavaScript to store and control all the timeouts you declare.
What can it be used for? Why, to stop the countdown!
Let’s say you have an application that fires off an event in 10,000 milliseconds (10 seconds). Half way through, your user decides that they don’t want that event to occur, so they press a button you have on your HTML page. You’ve got an ‘click’ event handler to capture that click, and now you have to cancel the original setTimeout(). How? Easy. Here’s the code:
clearTimeout(myHandle);
And that’s it. clearTimeout() takes only one argument, and that is the handle that you saved from the setTimeout() method. clearTimeout() will cancel the original setTimeout(), and your function will not execute.
But wait! There’s More!
You can even pass variables to your setTimeout() function from the setTimeout() method. It’s easiest to explain with some code:
const inputElementId = 'someInputElement';
const myHandle = setTimeout(displayValue, 10000, inputElementId);
function displayValue(elementId) {
const value = document.getElementById(elementId).value;
document.getElementById('results').textContent = `Within 10 seconds, you typed ${value}!`;
}
Notice that there is an extra argument after the millisecond argument in the setTimeout() method. This is a nice feature of setTimeout() – any arguments found after the millisecond argument are passed as arguments to your function.
In the example above, we’re passing the ‘id’ of an HTML <input> element on the screen to our setTimeout() function ‘displayValue’. That ‘inputElementId’ is the third argument to setTimeout(), and so will be the first argument in our ‘displayValue’ function.
What if you had more than one argument? Just list those out one after another. There’s no limit to the number of arguments – well, I guess there’s a memory limit – but I’m not going there.
Video
Tired of reading? Then watch our YouTube video on setTimeout();
Conclusion
Thanks for reading our little tutorial on the setTimeout() method.
Make sure you check us out at Boring JavaScript, or subscribe to our YouTube channel from the video above.
See you later!
Categories: Boring JavaScript Javascript
thevirtuoid
Web Tinkerer. No, not like Tinkerbell.
Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com
Leave a Reply