Javascript Debouncing And Throttling On Window Resize
Currently I have a handler on the Window object that listens to the resize event: window.onresize = function(){ doSomething(); } And I'm now trying to write two methods. The f
Solution 1:
functiondoSomething(timer) {
timer = timer || 1000;
var alreadyFired;
var timerID = null;
var interruptCounter = -100;
var fireLimit = 5;
var fired = 0;
functionDebounce() { //Old way, how I understood you inititallyif (alreadyFired != true) {
alreadyFired = true;
//Do stuffconsole.log("fired");
setTimeout(function() {
alreadyFired = false;
}, 1000); // Debouncing on 1 second
}
}
functionConstantFiring(firstIndicator) { // New way, as per comments.//Do stuffif (firstIndicator === true) {
console.log("fired for the 1st time");
} else {
console.log("Firing constantly every " + timer / 1000 + " seconds.");
}
}
functionThrottle() {
if (fired < fireLimit) {
fired++;
//Do Stuffconsole.log(fired);
setTimeout(function() {
fired--;
}, 3000); //Throttling on 5 fires per 3 seconds
}
}
functionInterruptTimer() {
if (interruptCounter === -100) {
//This runs only the 1st time window is resized, if you leave this//part out, the function will only fire 3 seconds AFTER the first//event fired and then consistantly unless the event occured in //last 3 seconds.
interruptCounter = 0;
ConstantFiring(true);
}
if (interruptCounter <= 0) {
interruptCounter++;
clearInterval(timerID);
timerID = null;
setTimeout(function() {
interruptCounter--;
if (interruptCounter <= 0 && timerID == null) {
timerID = setInterval(ConstantFiring, timer);
}
}, 3000); // Interrupt timer
}
}
//Change the following line to use a different function to test.var realFunction = InterruptTimer;
return realFunction;
}
window.onresize = doSomething(768); //Add a parameter representing a //period for the function timer (in milisec) //This is very optional, you can also hardcode// it into the doSomething fucntion in case// you want to add some other event.[parameter].
EDIT: Would also like to add that using a simple Global variable as an indicator is a much simpler solution, less confusing, but less "clean" from a "proper coding" type of view. If you do that then you don't have to deal with closures.
EDIT2: Updated the code and the link to reflect the desired behavior from the comments.
Post a Comment for "Javascript Debouncing And Throttling On Window Resize"