</> Code Corner

JavaScript · JS Browser BOM · Lesson 56

JS Timing

setTimeout, setInterval and clearing them.

The window object allows code to run at specified time intervals.

Example

<p id="clock" style="font-size:28px"></p>
<button onclick="clearInterval(timer)">Stop clock</button>
<button onclick="later()">Say hi in 2s</button>
<p id="demo"></p>
<script>
const timer = setInterval(function () {
  document.getElementById("clock").innerHTML = new Date().toLocaleTimeString();
}, 1000);
function later() {
  setTimeout(() => { document.getElementById("demo").innerHTML = "Hi!"; }, 2000);
}
</script>
Method Does
setTimeout(fn, ms) Runs fn once after ms milliseconds
setInterval(fn, ms) Runs fn repeatedly every ms milliseconds
clearTimeout(id) / clearInterval(id) Stops them

Keep reading “JS Timing”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋