Are there any issues with reassigning arguments as they’re passed to a function

In the following throttle function, timeout eventually turns into a number as it’s assigned to the setTimeout. I’m redefining it as false as it’s cleared, the code works.

I don’t notice anything on the surface, but wondering if there are any issues with doing things this way or there’s something I might be missing?

const throttle = (fn, delay) => {
  let timeout;

  return (...args) => {

    if(!timeout) { 
      timeout = setTimeout(() => {
        fn(...args);
        clearTimeout(timeout = false);
      }, delay);
    }

  }
};

Answer

The code:

clearTimeout(timeout = false)

is evaluated as:

timeout = false;
clearTimeout(timeout)

which means you call clearTimeout(false) and this is not correct. clearTimeout() should be called with a timeout ID returned by setTimeout().

It seems it works because you call clearTimeout() from the function that executes when the timeout expires. The call to clearTimeout() does not work but the timeout already expired and JavaScript clears it anyway.

Calling clearTimeout() from the timeout callback is not needed and does not help. The purpose of clearTimeout() is to call it before the timeout expires, to prevent the execution of the callback set with setTimeout().

Your code should be:

      timeout = setTimeout(() => {
        fn(...args);
        timeout = false;
      }, delay);