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.
setTimeout and setInterval.
✍️ 3 exercises + code challenge in this lessonJavaScript 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.
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.
<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>
Check what you learned in “JavaScript Timing”.
Run a function once after 2 seconds.
(showMessage, 2000);
How do you stop a setInterval timer?
Use setTimeout to log "Done" after 300 milliseconds.
Free sign-in required · Google login available
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