Timers in JavaScript are used to schedule functions to be called at a later time. It does so by setting up a timer which, when it’s done counting down, places its associated function into the environment’s event loop. As such, setTimeout
guarantees that the function won’t be fired before its specified time, but it cannot guarantee that it will be fired at that specific point in time too - if event queue has other functions waiting to be executed, then it will be delayed.
These timer functions are methods on the window
object and can be invoked as is:
document.body.style.background = "blue";
setTimeout(function () {
document.body.style.background = "yellow";
}, 2000);
Functions scheduled with setTimeout
can be cancelled with clearTimeout
:
var timedFunc = setTimeout(function () {
console.log("I'll never be executed");
}, 2000);
clearTimeout(timedFunc);
setTimeout
and clearTimeout
have cousins which execute their functions in regular intervals, called setInterval
and clearInterval
.
Debouncing
Timers in JavaScript can be used for debouncing to prevent event handlers from being invoked too frequently.
There are two effects that can be achieved here:
- To invoke the event handler after a pause in event firing
- To invoke the event handler at slower periodic intervals
An example of the first effect:
<button>Click me constantly</button>
<script>
var textarea = document.querySelector("button");
var timeout;
textarea.addEventListener("click", function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
console.log("You stopped clicking");
}, 500);
});
</script>
We clear the timeout to reset the timer.
An example of the second effect:
<script>
var scheduled = false;
window.addEventListener("mousemove", function (event) {
if (!scheduled) {
scheduled = true;
setTimeout(function () {
scheduled = false;
console.log("Mouse at " + event.pageX + ", " + event.pageY);
}, 250);
}
});
</script>
We check if scheduled
is true fist before creating a scheduled function. When the scheduled function fires, it resets scheduled
to false.