In this tutorial, we will learn how to work with timers in JavaScript. Having dealt with the timers, you can automatically perform any operations on the page after a specified period of time. For example, it will be possible to make an image slider in which the images will change every second.
To work with timers in JavaScript, the setInterval
function is used, which runs the given
code at certain intervals.
This function works as follows: as the first parameter, it takes function source code, and as the second parameter, the interval after which this function will be automatically called. The second parameter is in milliseconds (1000 milliseconds = 1 second).
Let's learn how the function works with an example. For example, let's write a code that every second will output something to the console.
First, let's make a function that outputs something to the console:
function timer() {
console.log('!');
}
And now with the help of setInterval
we will make
the function we created will be executed every second:
setInterval(timer, 1000);
function timer() {
console.log('!');
}
It is not necessary to create a separate function - you
can simply pass an anonymous function to the first
parameter of setInterval
, like this:
setInterval(function() {
console.log('!');
}, 1000);
Start a timer that every 3
seconds
will print something to the console.