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.

enru