Next.js Discord

Discord Forum

cannot figure out the calcalued lastExecutedTime in useThrottle

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
setTimeout(() => {
  const now = Date.now();
  const timeElapsed = now - lastExecuted.current;

  if (timeElapsed >= delay) {
    setThrottledValue(value);
    lastExecuted.current = now;
  }
}, delay - (Date.now() - lastExecuted.current));


My confusion lies in the if (timeElapsed >= delay) and delay - (Date.now() - lastExecuted.current). It seems that there are two calculations for checking time. Why?

2 Replies

Roseate Spoonbill
I'm not sure what implementation of throttle this is, but simply based on the code you provided I can tell that:
- The delay in setTimeout second parameter is not a check, simply information, when the callback needs to be executed
- The actual timeElapsed check in callback makes sure, that there wasn't another call queued between between executions.

If you call this once, the check inside is not needed, but let's assume this scenario:
- delay is 1s
- first call happens and setTimeout is scheduled 1s in the future
- second call happens 0.5s after the first and is also scheduled
- both will try to fire at the same time:
- first will be executed as timeElapsed is 1s and update the lastExecuted time
- second will be executed, but will notice, that timeElapsed since lastExecuted is 0s, so will not update the throttled value
Ofc I might be wrong, it's just assumption on quick code analysis without wider context, so please don't quote me on that 😉