JavaScript Timeouts and Intervals
Timeouts and intervals let you execute pieces of code at specific times — they’re really useful! Learn how to use them in this article.

Timeouts and intervals let you execute pieces of code at specific times — they’re really useful! Learn how to use them in this article.
Before we begin…
I highly recommend following along in this article! It’ll help you understand and remember the concepts better. To get started, create this HTML file and then open it up in your browser:
<html> <head> <title>JavaScript — Timeouts and Intervalstitle> head> <body> <script> // Exciting code coming soon! script> body> html>
If you want to try out some JavaScript, you can put it in thetag, save, reload the page and see what happens! In this tutorial, I’ll be using
console.log
— this prints stuff to the console so you can see it. To open up the console:
- Right-click
- Go to ‘Inspect Element’
- Go to the ‘Console’ tab
You’re all set up now! Enjoy…
Timeouts
Timeouts let us execute some code after a certain period of time. We can create a timeout using the setTimeout
function:
var myTimeout = setTimeout(/* We'll fill this soon! */);
setTimeout
has two inputs — the first input is a function which we will use to store the code that we want to run. Let’s create a function that we can use! (make sure you have the console open (see above), so you see the console.log
)
function myTimeoutFunction() {
console.log('3 seconds have passed!');
}
var myTimeout = setTimeout(myTimeoutFunction);
If you run your code now, it will log this instantly — because we haven’t set how long we want to wait for! We do this using the second input of setTimeout
— this is the amount of time that we want to wait in milliseconds. A millisecond is 1/1000 of a second. So if we want to wait 3 seconds, we’d set it to 3000
! Let’s try it out…
function myTimeoutFunction() {
console.log('3 seconds have passed!');
}
var myTimeout = setTimeout(myTimeoutFunction, 3000);
Run your code — now it logs three seconds after loading the page!
You can tweak the number of milliseconds to change how long it waits :)
Intervals
Intervals let you run a piece of code over and over again, with a particular amount of time in between each repetition. Similarly to setTimeout
, it has two inputs — the function that you want to repeat, and the amount of time that you want to wait (in between each repetition).
See if you can make our code console.log
something every 5 seconds using the information above (if you can’t that’s fine
Apa Reaksimu?






