How to Call a Function After a Specific Time Period With JavaScript

There are a couple of ways we can call or run a function after a specific time period with JavaScript. I’ll show you two JavaScript time event methods, setTimeout() and setInterval().

The difference between these time event methods is:

  • setTimeout() runs a function, once, after waiting a specified number of milliseconds
  • setInterval() keeps running a function continuously at a specified time interval

Let’s look at a simple example of each.

JavaScript setTimeout() example

Add the following code to your coding playground’s JavaScript console. You can use your browser’s console if you want:

setTimeout(function() {
	alert('Hello there!')
}, 3000)

3000 is milliseconds (ms) so the above is 3 seconds. This code will run, 3 seconds after your initial page load, and show an alert message saying “Hello there!”.

JavaScript setInterval() example

Add the following code to your coding playground’s JavaScript console. You can use your browser’s console if you want:

setInterval(function() {
	alert('Hello there!')
}, 3000)

This code will execute again and again every 3 seconds.


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 😊

Kofi