Reputation: 1495
From the Mozilla site on resize
, I don't understand the below example of how resizeTimeout
is made to null
inside the setTimeout
function. What purpose does that serve? By declaring both var resizeTimeout;
and then setting it to null
, the conditional of (!resizeTimeout)
will be true, so what difference does it make to set it to null
?
(function() {
window.addEventListener("resize", resizeThrottler, false);
var resizeTimeout;
function resizeThrottler() {
// ignore resize events as long as an actualResizeHandler execution is in the queue
if ( !resizeTimeout ) {
resizeTimeout = setTimeout(function() {
resizeTimeout = null;
actualResizeHandler();
// The actualResizeHandler will execute at a rate of 15fps
}, 66);
}
}
function actualResizeHandler() {
// handle the resize event
...
}
}());
Upvotes: 0
Views: 679
Reputation: 1102
This is a common technique called "throttling," as the function name suggests. This makes it so the resize handler will only be called at most every 66 milliseconds.
If the user is resizing the window, it will keep firing that event and triggering the resizeThrottler function constantly. However, if you executed the actualResizeHandler every time the resize event was triggered, your page would get bogged down.
Since the resizeTimeout is being set to null WITHIN the timeout function, the expression !resizeTimeout
will only be true at most every 66 milliseconds. Once those 66 milliseconds are up, you can set another one.
Upvotes: 2