Run JavaScript code or call a function after n seconds

In this post, we are going to run our JavaScript code or call a function after a specific time or after n seconds after the window load.

Suppose we want to alert a message after n seconds of window load in JavaScript. Well, we can do it easily using JavaScript. JavaScript has a method which is setTimeout() method that we are going to use to delay in running our JavaScript code or delay in the function call. We can use this method to call our function after a specified time or run our JavaScript code.

Below is an example which will alert a message after 7 seconds:

alert("This is the alert message appear after 7 seconds");
}, 7000);  // Set the time out to 7 seconds

If we run the above JavaScript code then we will see the alert message appear after 7 seconds.

Run your JavaScript code every n seconds using setInterval() method

Validating phone numbers in JavaScript

Below is another example where we are calling a function inside setTimeout method:

setTimeout(delayLoad, 4000);
function delayLoad() {
  alert("This alert message appear after 4 seconds");

In the above code we have created a JavaScript function and then call it through setTimeOut method. If we run the code, then it will show the alert message after 4 seconds of window load. Here we have called a function after for seconds.

Leave a Reply

Your email address will not be published. Required fields are marked *