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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Are there any issues with reassigning arguments as they’re passed to a function without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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);
We are here to answer your question about Are there any issues with reassigning arguments as they’re passed to a function - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji