Javascript – run a function at regular interval

Javascript setInterval can be used to make repeated calls to a function or code with fixed interval. If there is a possibility that function logic can take longer that interval (it may happen in AJAX calls), it is better to use setTimeout.

// delay in milliseconds
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);

Here is an example where a function will update time in a specified div. We’ll use setInterval with 1 second interval to run the function periodically. If user clicks on stop button, the clearTimeout call is made.
<div id="id1"></div>
<button onclick="clearTimeout(intervalId);">stop</button>
<script type="text/javascript">
// execute every 1000 milliseconds
var intervalId = setInterval(update, 1000);
function update() {
  document.querySelector("#id1").innerHTML = (new Date()).toLocaleTimeString();

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments