How to set a timer in jQuery?

By Faruque Ahamed Mollick

In this post, we are going to learn a simple yet useful jQuery trick. here we are going to see how to set a timer using jQuery.

In a project, it may be needed to set a timer which will appear after a certain time.

Run JavaScript code or call a function after n seconds

For example, we want a jQuery alert message will appear after 5 seconds of page load. In this case, we need to set a timer.

jQuery code snippet to set a timer

To set a timer in jQuery, we can use the setTimeout method. The jQuery setTimeout() method is able to set a time and after that certain time, the code will run.

Below is an example where we will show an alert message which will appear after 5 seconds of page load:

$(document).ready(function(){
      setTimeout(function(){
          alert("This is the alert message for timer");
      }, 5000);
 })

In the above code, we have used the jQuery $(document).ready() method so that we can count the time after page loading complete.

Run JavaScript code or call a function after n seconds

Delay in loading external JavaScript file

Now if you run the code on your browser, you will see the alert message appear after 5 seconds of page load. We can task run any of our JavaScript code which will be run after a specific time by setting a timer using JavaScript setTimeout() method.

Leave a Reply

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