I have an event handler function which every time is triggered should clear a setTimeout()
and set a new timeout.
Now the callback for the timeout has to take few arguments, for example the event object received by the handler.
And that's it. I did it, but I believe that my solution is not optimal, nor the cleanest:
let timer;
const handler = (event, type) => {
clearTimeout(timer);
if(type === 'CHANGE') timer = setTimeout(callback, 500, { argumentsForTheCallBack });
}
As you can see I have my timer
as a global variable, even though I need it only in the event handler.
Is there a way to make the handler self-contained?
I am interested in ECMAScript solutions as well as solution using React.js syntax (in my original code the callback is a dispatcher for a useReducer
hook)