Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution for throttle decorator is incorrect. (Decorators and forwarding, call/apply) #3613

Open
void5253 opened this issue Nov 12, 2023 · 0 comments

Comments

@void5253
Copy link

void5253 commented Nov 12, 2023

Original code: https://javascript.info/call-apply-decorators#throttle-decorator

Here's a small code snippet to show where it doesn't work.

function f(a) { console.log(a) };

let g = throttle(f, 1000);

for(let i = 0; i < 1e8; i++) g(i);

Expected Output

1, 249204, 452039, ... , 9999999 (These are random increasing numbers)

Output

1, 9999999

Why does it fail?

function wrapper() {

    if (isThrottled) { // (2)
      savedArgs = arguments;
      savedThis = this;
      return;
    }
    isThrottled = true;

    func.apply(this, arguments); // (1)

    setTimeout(function() {
      isThrottled = false; // (3)
      if (savedArgs) {
        wrapper.apply(savedThis, savedArgs);
        savedArgs = savedThis = null;
      }
    }, ms);
  }

In above, isThrottled = false assignment is done inside setTimeout callback. However, only one callback is pushed into task queue and it isn't executed until stack is empty (for loop has to be completed).
isThrottled is always true => setTimeout isn't called => one callback (that was registered for initial false isThrottled) => cb executed at end and outputs last value => output: 1, 9999999.

Correct Solution: #2844

This PR giving an alternative solution.

@void5253 void5253 changed the title Throttle task incorrect solution. (Decorators and forwarding, call/apply) . (Decorators and forwarding, call/apply) Nov 13, 2023
@void5253 void5253 changed the title . (Decorators and forwarding, call/apply) Solution for throttle decorator is incorrect. (Decorators and forwarding, call/apply) Nov 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant