How to use setTimeout method in JavaScript??

If you want a pop up ads that shows up about 1 minute after users visiting your Website, "SetTimeout" method in JavaScript will help you.
So I'm going to tell you how to code SetTimeout method in JavaScript.

The basic of the setTimeout method


The setTimeout method is used when you want to execute code after a certain amount of time has passed. Specifically, you set a time interval in seconds or minutes, and then specify the function to be executed after that time has elapsed

Code for the setTimeout method

The basic syntax for the setTimeout method is as follows:

window. SetTimeout ( function, delay time );

In JavaScript, possible to omit the initial "window."

SetTimeout ( function, delay time (in milliseconds) );

Time to run the code

Alright, let's try and run the code.

SetTimeout ( function () { console.log ('Hello') }, 3000 )


The code is to show "Hello" on console 3000 milliseconds later which means 3 seconds.

You can see that "Hello" showed up on console after 3 seconds later in the video.

Next, let's customize the function part a bit and display an alert.

I only add the code 'alert...'.

setTimeout ( function () {
    //console.log(count); //comment out
    window.alert('Hello'); //"window." is possible to omit
}, 3000);

You can see that "Hello" alert on the screen showed up on after 3 seconds later in the video down below.

The setTimeout method can be used to display pop-ups, but its drawback is that it only executes once. So, if you want to repeat the process, you need to handle a new setTimeout method each time.

For those who want to repeat timeouts, the "setInterval" method is recommended.

Next time, I'll talk about setInterval method, which is similar.