Please see code snippet. It has nothing to do with throttle concept.
I declare click event like btn.addEventListener("click", outerFunction);. It gets invoked but the statement 'console.log("button is clicked outer function " + e.pointerType)' does not get executed.
While if I declare function inline then it works as expected.
So i am not able to understand why it does not work when it is declared in outerfunction
const btn = document.querySelector("#throttle");
const btn2=document.querySelector("#newthrottle");
// Throttling Function
const throttleFunction = (func, delay) => {
// Previously called time of the function
let prev = 0;
return (...args) => {
// Current called time of the function
let now = new Date().getTime();
// Logging the difference between previously
// called and current called timings
console.log(now - prev, delay);
// If difference is greater than delay call
// the function again.
if (now - prev > delay) {
prev = now;
// "..." is the spread operator here
// returning the function with the
// array of arguments
//debugging arguments
var inputArguments = [...args]
console.log("arguments" + inputArguments);
return func(...args);
}
};
};
function outerFunction(e) {
console.log('Outer function')
throttleFunction(((e)=>{
console.log("button is clicked outer function " + e.pointerType)
}),1500)
}
//this does not work
btn.addEventListener("click", outerFunction);
//this works like a charm
btn.addEventListener("click", throttleFunction((event)=>{
console.log("button is clicked throttle " + event.pointerType)
}, 1500));
function onButtonClick(e){
console.log('Hello World onbutton Click' + e);
}
btn2.addEventListener("click", onButtonClick);
You can do something like this -
function outerFunction(e) {
console.log('Outer function')
const t = throttleFunction((e)=>{
console.log("button is clicked outer function " + e.pointerType)
},1500);
t();
}
But it will be undefined so instead of returning an anonymous function try calling the callback function.