Delay before execution in JavaScript

Let's now look at the setTimeout function, which allows you to make a delay before running the code. This delay, unlike the setInterval function, will happen only once.

The first parameter of setTimeout takes the source code of the function, and the second parameter is the delay in milliseconds before starting this function.

Let's see how the function works on some example. Let's say we have a button like this:

<input type="submit" id="elem">

Get a reference to our button into a variable:

let elem = document.querySelector('#elem');

Let's now make it so that when the button is pressed, alert is displayed on the screen, but not immediately, but after 3 seconds after pressing:

elem.addEventListener('click', function() { setTimeout(function() { alert('!'); }, 3000); });

Given a paragraph. Write code that will display a message in this paragraph 10 seconds after the page loads.

Timer start

Although the setTimeout function is not designed to create timers, you can still make them with it if you use recursion:

let i = 0; function timer() { setTimeout(function() { console.log(++i); timer(); // let's call ourselves }, 1000); } timer();

You can stop such a timer simply without letting the recursion happen:

let i = 0; function timer() { setTimeout(function() { console.log(++i); if (i < 10) { // runs only if counter is less than 10 timer(); } }, 1000); } timer();

Print the number 0 to the console. After one second - print the number 1, after two seconds - print the number 2, after 3 seconds - print the number 3. And so on ad infinitum.