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

In many times it is needed to run a JavaScript code periodically with a time interval. For example, in live online conversation or messaging system it needs to send AJAX request in every few seconds to check if there are any new message has been sent from the sender or not. In that case, the JavaScript AJAX code run periodically.

Suppose you want to run your JavaScript code also every n seconds. how to do it? How can you run your JavaScript code on every n second?

How to disable your website accessing from iframe using JavaScript?

How to generate a random password in JavaScript?

Here in this post, we are going to run our JavaScript code periodically after every n seconds which is going to give you the idea. Here we are going to alert a message in the browser every 4 seconds.

Here we are going to use the Window setInterval() method.

The window setInterval method calls a JavaScript function or evaluates an expression at a declared interval. We set the interval in milliseconds.

Now if you want to run your JavaScript code every n seconds then you can use setInterval() method. Here in the example, we are going to alert a message every 4 seconds. For simplicity and easy understanding, we are going to use alert message. below is the javaScript code:

setInterval(function() {
    alert('I will appear every 4 seconds');
}, 4000);   // Interval set to 4 seconds

Now you can put any of your code that you want to run in every 4 seconds:

setInterval(function() {
    // Your JavaScript code will be here
}, 4000);   // Interval set to 4 seconds

Show live preview of HTML textarea with JavaScript

Alternative process

There is another alternative process using the same setInterval() method to run your JavaScript code periodically. Here you will call a function within the setInterval method and the function will come from outside of this method. below is the code:

setInterval(my_alert_func, 3000); // Set to 3 seconds
function my_alert_func()
  alert('I am an alert message appear in every 3 seconds');


That’s it. We have just written our simple JavaScript interval code which can run any of our JavaScript code in every second.

Leave a Reply

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