Javascript settimeout example

Javascript setTimeout can be used to scheduled a function or code to run at a specified delay. This is pretty powerful API and can be used to run something in loop by making another setTimeout call at the end of the scheduled function/code. The handle returned can be use to clearTimeout later if needed.



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

Here is an example where a function will update time in a specified div and then call setTimeout again with 1 second delay to run same function. If user clicks on stop button, the clearTimeout call is made.

<div id="id1"></div>
<button onclick="clearTimeout(timeoutId);">stop</button>
<script type="text/javascript">
var timeoutId;
function update() {
  document.querySelector("#id1").innerHTML = (new Date()).toLocaleTimeString();
  // execute after 1000 milliseconds
  timeoutId = setTimeout(update, 1000);
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments