How to delay in loading JavaScript code?

In this tutorial, we are going to see how to Delay in loading our JavaScript code on a web page.

Suppose we want to delay our JavaScript code for few seconds. Here we are going to see an example which will run some of our particular JavaScript code by delaying 6 seconds.

To make it simple and easy to understand we are going to show a JavaScript alert message that will appear in 6 seconds of delaying. Below is the code that will show an alert message in 6 seconds delay after the window load:

setTimeout(function() {
   alert('This alert message delayed 6 seconds');
}, 6000);

In the above code, we have used the setTimeout() JavaScript window method. The setTimeout function calls a function after a particular time that is provided as milliseconds. In our case, we have set setTimeout to 6000 milliseconds or 6 seconds (1seconds = 1000 milliseconds).

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

Set a default image for broken or Unavailable image URL in JavaScript

We can also create a separate function and call it inside the setTimeout() method just we can see below:



setTimeout(function_to_call, 6000);

function function_to_call() {
   alert('This alert message delayed 6 seconds');
}

The above function will also alert the same message after 6 seconds of the window load.

The setTimeout method only calls the function once. If you want the repetition or periodically executing the function then you can do it by following this tutorial – Run your JavaScript code every n seconds using setInterval() method.

Leave a Reply

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