DEV Community

loading...

The setTimeout() method in JavaScript

davidbell_space profile image David Bell Originally published at davidbell.space ・1 min read

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

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

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

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

Twitter

Discussion

pic
Editor guide