By default, all JavaScript code runs synchronously. This means that the statements are evaluated from top to bottom, one after another.
console.log('hello');
console.log('synchronous');
console.log('world');
The strings will be printed to the console in the same order as they appear.
hello
synchronous
world
Starting the timer with setTimeout
To delay the execution of some function in JavaScript, you can setTimeout
. In the base case it accepts two parameters:
callback
- the function that should be calleddelay
- in milliseconds
setTimeout
sets the timer and calls callback
function after delay
milliseconds.
The callback
function will be executed only once. If you’re looking for repeated execution, you should use
setInterval.
console.log('hello');
setTimeout(() => {
console.log('async message that appears on the screen in 1 second')
}, 1000);
console.log('world');
The messages will appear in the following order:
hello
world
async message that appears on the screen in 1 second
Common setTimeout
mistakes
In JS, the first argument passed to setTimeout
should always be a function. If you just write console.log
- it won’t work properly.
console.log('hello');
setTimeout(console.log('failed async message'), 1000);
console.log('world');
This code snippet is broken. The output of failed async message
won’t be delayed as the console.log
will be evaluated synchronously and return undefined
.
Then, there are 2 possibilities, which depend on the environment that your code runs in:
-
Node.js - error
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
-
Browser - no error, but there will be no delay and the order of the messages will be different
hello failed async message world
Read more JavaScript tutorials or Learn Full-Stack JS from scratch!