JavaScript Timing

setTimeout and setInterval.

✍️ 3 exercises + code challenge in this lesson

JavaScript can run code later or repeatedly:

  • setTimeout(fn, ms): run once after a delay.
  • setInterval(fn, ms): run repeatedly every ms milliseconds.
  • clearTimeout(id) / clearInterval(id): cancel them.

1000 milliseconds = 1 second.

Key Takeaways: JavaScript Timing

Mastering JavaScript Timing helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Timing Code Example

JavaScript
<h1 id="clock">--:--:--</h1>
<p id="note"></p>
<button onclick="stop()">Stop clock</button>

<script>
  const timer = setInterval(() => {
    document.getElementById("clock").textContent = new Date().toLocaleTimeString();
  }, 1000);

  setTimeout(() => {
    document.getElementById("note").textContent = "This message appeared after 2 seconds.";
  }, 2000);

  function stop() { clearInterval(timer); }
</script>
Free sign-in required · Google login available

JavaScript Timing Practice Exercises

Check what you learned in “JavaScript Timing”.

/ 3 solved
Fill in the blank

Run a function once after 2 seconds.

(showMessage, 2000);
✓ Correct! Not quite. Try again.
Multiple choice

How do you stop a setInterval timer?

✓ Correct! Not quite. Try again.
Code challenge

Use setTimeout to log "Done" after 300 milliseconds.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services