codegurukool.com · Free coding tutorials & online compiler

Home › JavaScript Tutorial › Timers

Timers

Run code later or repeatedly.

setTimeout runs once after a delay in milliseconds. setInterval repeats, and clearInterval stops it.

Commands in this lesson

setTimeout

Definition: Runs a function once after a delay in milliseconds.

Syntax:

setTimeout(function, ms);

Example:

setTimeout(function(){ console.log("later"); }, 1000);

setInterval

Definition: Runs a function again and again every given milliseconds.

Syntax:

setInterval(function, ms);

Example:

var i = 0;
var t = setInterval(function(){
  console.log(++i);
  if (i === 3) clearInterval(t);
}, 500);

Example code

<h2 id="t">0</h2>
<script>
  let n = 0;
  const id = setInterval(() => {
    t.textContent = ++n;
    if (n === 10) clearInterval(id);
  }, 500);
</script>

Run this code in the online editor

← ObjectsForm validation →