Setting and clearing setTimeout() inside of an event handler 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) =&gt; {

    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)
Since you mention useReducer React hook I will assume you are using a functional component and thus can use other React hooks.
I suggest:

Use a React ref to hold a reference to the timer (versus global variable).
Use an useEffect hook to clear any running timeouts in the case the component unmounts before the timeout expires. Provide an empty dependency array so the effect callback is called only once. Here it is just to return the cleanup function to clear any running timeouts.

Code:
import { useEffect, useRef } from 'react';

...

// in component
const timerRef = useRef(null);

useEffect(() =&gt; {
  return () =&gt; clearTimeout(timerRef.current);
}, []);

const handler = (event, type) =&gt; {
  clearTimeout(timerRef.current);

  if (type === 'CHANGE') {
    timerRef.current = setTimeout(callback, 500, { argumentsForTheCallBack });
  }
}

Why provide cleanup function from useEffect?
If you attempt to update state of an unmounted component you'll get a React warning stating:

Warning: Can’t perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect
cleanup function.

It's just a warning though, so if you are ok with the warning in non-production builds and you know you don't actually have a memory leak (open sockets, connections, subscriptions, etc...) then you can likely safely ignore them.
In general you should strive to write code that doesn't generate warnings though, and this is a warning that is easily preventable.