h2non / hu

Small, generic functional helper library for node.js and browsers
MIT License
20 stars 3 forks source link

Debounce bug #31

Closed rafinskipg closed 10 years ago

rafinskipg commented 10 years ago

Hi Mr h2non

I 've detected a bug in the debounce function when I do

var createBonus = hu.debounce(function(){
    console.log('creating boinus', bonuses.length);
    bonuses.push(EL.getEntity('bonus',[canvas.width, Math.random() * (canvas.height - 39)]));
  }, 5000);

the createBonus() function is used on a canvas game, then it's crucial that it's only being called after X seconds. Otherwise is called like 60 times per second.

What is happening right now is (on the game loop)

What should be happening is

If you are too busy, i can try to look into it this weekend, otherwise i will be very grateful for your fix

cheers

rafinskipg commented 10 years ago

Following "lodash" example:

Debounce

Creates a function that will delay the execution of func until after wait milliseconds have elapsed since the last time it was invoked

Throtle

Creates a function that, when executed, will only call the func function at most once per every wait milliseconds.

I was not seing the big difference between them ,so i searched for more info

What does it is usually understood as debounce or throtle ?

Debounce: Think of it as "grouping multiple events in one". Imagine that you go home, enter in the elevator, doors are closing... and suddenly your neighbor appears in the hall and tries to jump on the elevator. Be polite! and open the doors for him: you are debouncing the elevator departure. Consider that the same situation can happen again with a third person, and so on... probably delaying the departure several minutes.

Throttle: Think of it as a valve, it regulates the flow of the executions. We can determine the maximum number of times a function can be called in certain time. So in the elevator analogy.. you are polite enough to let people in for 10 secs, but once that delay passes, you must go!

rafinskipg commented 10 years ago

Yeah, maybe was to my missunderstanding of debounce behaviour.

It stores all the requests to that function and launches them after 5 seconds.

Closing!