JavaScript Timing Events
Timing Events let you run code:
- After a Delay
- Or Repeatedly
| Function | Description |
|---|---|
| setTimeout() | (runs once) |
| setInterval | (runs repeatedly) |
| clearTimeout | Clears the timeout |
| clearInterval() | Clears the inteval |
The setTimeout() Method
The setTimeout() method executes a function after a delay in milliseconds.
Syntax
const timeoutID = setTimeout(function, delay, p1,...,pN);
Example
<button id="btn">Start</button>
<p id="demo"></p>
<script>
document.getElementById("btn").addEventListener("click", function () {
setTimeout(showMsg, 2000);
});
function showMsg() {
document.getElementById("demo").innerHTML = "Hello after 2 seconds!";
}
</script>
Try it Yourself »
Note
The setTimeout() method is a core part of asynchronous JavaScript,
allowing code execution to be scheduled without blocking the main execution thread.
The SetInterval()Method
Syntax
With single quotes:
<element
event='some JavaScript'>
With double quotes:
<element
event="some JavaScript">
Example
setInterval() used with
clearInterval():
<button id="start">Start Counter</button>
<button id="stop">Stop</button>
<p id="counter">0</p>
<script>
let myInterval;
let count = 0;
document.getElementById("start").addEventListener("click", function () {
myInterval = setInterval(counter, 1000);
});
document.getElementById("stop").addEventListener("click", function () {
clearInterval(myInterval);
});
function counter() {
count++;
document.getElementById("counter").innerHTML = count;
}
</script>
Try it Yourself »
A Simple Clock
Example: Simple clock
<p id="clock"></p>
<script>
setInterval(showTime, 1000);
function showTime() {
const d = new Date();
document.getElementById("clock").innerHTML =
d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}
</script>
Try it Yourself »