How to repeat a task after fixed time interval in javascript / How to call a function every n seconds in javascript

Scenario
Many times you want to perform some task repeatedly after a definite time interval or call a particular function after every fixed time elapse. Example, checking for the status of completion of a process and showing the result when the process completes or displaying some message on the browser after every few seconds etc.

Javascript way
In javascript a task can be repeated using setTimeout method. This method takes 2 arguments, first one is the task which needs to be done. This task is provided in the form of a function. Second argument is the time after which the task will be repeated. Time is given in milliseconds.

Usage
Suppose you need to display an alert message after every five seconds. Using setTimeout method this will be accomplished as below.

<script>
   // task to be repeated
   function showAlert() {
      alert(“Welcome!!”);
}

   // show alert after every 5 seconds
   setTimeout(showAlert, 5000);
</script>

setTimeout function returns a numeric integer which is the id of the timer set up by this function. This id is used to stop the timer.

Other Usages
Above was the standard way of using setTimeout function but there are other variants of using it. All of them differ in the way, the function(which needs to be called repeatedly) is passed to it. These methods are outlined below.

1. It is possible to provide the task to be repeated inline to setTimeout function instead of writing it as a separate function as shown below.

<script>
   // provide inline function
   setTimeout(function() { alert(“Repeat”); }, 5000);
</script>

2. You can also assign the function(which contains the task to be repeated) to a variable and then supply that variable to setTimeout function as shown below.

<script>
    // assign function to a variable
   var functionRef = function
showAlert() {
                                   alert(“Welcome!!”);
}

   // pass variable as reference to the function
   setTimeout(functionRef, 5000);
</script>

3. ES2015(or latest javascript) introduces the concept of arrow function. It can also be used as the first argument to setTimeout function as shown below.

<script>
   // provide repeated task as arrow function
   setTimeout(() => { alert(“Repeat”); }, 5000);
</script>

Stopping Repeated Task
Once a task is started it keeps on repeating till it is not stopped. It is stopped using another function clearTimeout which takes the identifier returned by the setTimeout function. Example,

<!– stop timer on button click –>
<button
onclick=”stopTimer()”>Stop</button>

<script>

   // show alert after every 5 seconds
   var timerId = setTimeout(function() { alert(“Repeat”); }, 5000);

   function stopTimer() {
// stop the timer
      clearInterval(timerId);
</script>

Timer is started as soon as page is loaded and a button is used to stop the timer. An onclick event is bound to the button which calls a function stopTimer. This function calls clearInterval method passing it the id of timer returned by setTimeout function.

Using quotes and parenthesis in setTimeout
Many people are confused with the usage of quotes and parenthesis with the function name(which contains the task) provided in setTimeout function. Following are the valid usage of quotes and parenthesis.

With parenthesis but without quotes

   setTimeout(showAlert(), 5000);

If the function is used this way, then it will only be called once but not in a repeated manner.

Without parenthesis and quotes

   setTimeout(showAlert, 5000);

This is a valid usage of the function and will trigger the function showAlert after every 5 seconds.

With parenthesis and quotes

   setTimeout(“showAlert()”, 5000);

This is also a valid usage of the function and will trigger the function showAlert after every 5 seconds.

Without parenthesis but with quotes

   setTimeout(“showAlert”, 5000);

This is an invalid usage of the function. When used this way the function not even be called once as it will be treated as a string.

Note: This post sets a function to be called repeatedly by using setTimeout directly. You can also set repeated calls on an event such as on a click of button. For this, move setTimeout to another function and attach this function with the onclick event of a button just as we did for stopping the timer.

Leave a Reply