DEV Community

Cover image for JavaScript setTimeout, how to delay the function execution
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com on

JavaScript setTimeout, how to delay the function execution

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');
Enter fullscreen mode Exit fullscreen mode

The strings will be printed to the console in the same order as they appear.

hello
synchronous
world
Enter fullscreen mode Exit fullscreen mode

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 called
  • delay - 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');
Enter fullscreen mode Exit fullscreen mode

The messages will appear in the following order:

hello
world
async message that appears on the screen in 1 second
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • Browser - no error, but there will be no delay and the order of the messages will be not as expected
  hello
  failed async message
  world
Enter fullscreen mode Exit fullscreen mode

Learn Full Stack JavaScript

Top comments (0)