JSFiddle - React, Tailwind, and code Playground
JavaScript
function doSomething(timer) {
timer = timer || 1000;
var alreadyFired;
var timerID = null;
var interruptCounter = -100;
var fireLimit = 5;
var fired = 0;
function Debounce() { //Old way, how I understood you inititally
if (alreadyFired != true) {
alreadyFired = true;
//Do stuff
console.log("fired");
setTimeout(function() {
alreadyFired = false;
}, 1000); // Debouncing on 1 second
}
}
function ConstantFiring(firstIndicator) { // New way, as per comments.
//Do stuff
if (firstIndicator === true) {
console.log("fired for the 1st time");
} else {
console.log("Firing constantly every " + timer / 1000 + " seconds.");
}
}
function Throttle() {
if (fired < fireLimit) {
fired++;
//Do Stuff
console.log(fired);
setTimeout(function() {
fired--;
}, 3000); //Throttling on 5 fires per 3 seconds
}
}
function InterruptTimer() {
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]...