How to Run a Function After a Specified Amount of Time, with JavaScript

You can delay the execution of any JavaScript function by using the built-in setTimeout() method.

Let’s say you want to show an alert dialog after 3 seconds.

First you need to convert 3 seconds into milliseconds (ms), which is 3000ms, and then set up the function:

setTimeout(function() {
  alert("That’s 3 seconds!")
}, 3000)

The above is an anonymous (nameless) function, which isn’t too practical in real life, because it can only be used once, and it’s nondescriptive.

Here’s the exact same functionality, but in a named, function expression:

const delayThreeSeconds = function() {
  alert("That’s 3 seconds!")

setTimeout(delayThreeSeconds, 3000)

Now you can reuse your delay function anywhere in your project by referencing the delayThreeSeconds variable.

setTimeout delay is suggestive — not precise

Most people don’t know that the time you specify in setTimeout is the minimum function-execution delay — not the exact amount of it will take to execute.

So if you specify 3000ms (3 seconds), it could take much longer before your function executes because JavaScript is synchronous, it runs one task at a time.

So if your website has a bunch of other JavaScript function tasks that are set to execute before your setTimeout function, those tasks will have to complete first, and that could take anywhere from a few milliseconds, to several seconds.

Something that could cause a huge delay is if one of your functions depends on loading a huge script from an external source to complete. These are the types of traps you can fall into as a beginner, or even as an experienced developer.

All this makes setTimeout somewhat unpredictable, or at least unreliable if you need pin-point precision.

A simple way to avoid this problem (mostly)

If there’s a specific function in your project where precise timing critical, set it to run before any other functions. This will at the very least ensure that your most important function runs as fast as possible.

However, even if your most critical function is set to execute before any other code there could still be some execution delay.

For example, if the user has a bunch of addons/extensions installed in their browser. That software runs on JavaScript (among other things) and it’s impossible to predict how much or if that will cause a delay on your website’s code execution.

All this is why performance is such an important topic to focus on, and why testing your code’s performance in all browsers and on multiple devices is crucial to provide consistent user experiences.

Good to know: what you learned today also applies to the setInterval method, the difference is that it runs repeatedly, — setTimeout runs once.

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊


Share & Discuss on