The setTimeout() method in JavaScript
David Bell
Posted on October 21, 2020
If you want to run something once after a set time use setTimeout()
Set Timeout
setTimeout()
is a window method available to us. It takes two things:
- A callback function
- Time in milliseconds
setTimeout(() => {
console.log('1 second!');
}, 1000);
// '1 second!'
In the example an anonymous function () =>
is passed in. The time in milliseconds is passed at the very end }, 1000)
. 1 second
is printed to the console after 1 second has passed once the rendered.
You can also pass a function into setTimeout
.
const oneSec = () => {
console.log('1 second');
};
// '1 second'
setTimeout(oneSec, 1000);
The function oneSec()
is ran after 1000 milliseconds.
setTimeout()
is a good way for understanding the asynchronous
nature of JavaScript. See the example below.
const oneSec = () => {
console.log('1 second');
};
setTimeout(oneSec, 1000);
console.log('Me first!');
// 'Me first!'
// '1 second'
In the example Me first!
is printed to the console. before 1 second
even though the setTimeout is written before the console.log
. The code will call oneSec
after 1000 milliseconds but in the mean time it continues to read the rest of the code. This is why it's called a callback
function.
Let's connect
Posted on October 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 24, 2024
November 22, 2024