Remy Sharp's function throttler

2019-09-14 16:28发布

问题:

trying to use a throttling function created by Remy Sharp (http://remysharp.com/2010/07/21/throttling-function-calls/)... it works in the standard use like so:

$('.thing').click(throttle(function() { 
   console.log('api call'); 
}, 300);

Which is pretty neat, but I wanted to be able to throttle a specific part of code within a function, not on the entire click event, like so:

$('.thing').click(function() { 
    console.log('hello!'); 

    throttle(function() { 
        console.log('api call'); 
    }, 300); 

});

But I don't quite understand why it doesn't work. The throttle code returns a function so if I proceed the throttle call with .apply(this, arguments); then type 'hello', the function is called 5 times rather than once as the timer within the throttling function isn't being overwritten.

Sifted through the jQuery click code but couldn't really find anything. I'm guessing jQuery creates one instance of it and then recalls the same instance so the same timer is there?

Does anyone understand this and why it happens like so?

Thanks, Dom

回答1:

You're doing it wrong ;-)

Here's the solution on jsbin: http://jsbin.com/elabul/edit

The throttle method returns a function that will throttle the number of times it's called. So you need to capture that bad boy in a variable and call it from inside your click handler, as such:

var inputThrottle = throttle(function () {
  console.log('api call');
}, 250);


$('input').keyup(function () {
   console.log('test');
   inputThrottle();
});


回答2:

you need to call returned from throttle function:

$('.thing').click(function() { 
    console.log('hello!'); 

    (throttle(function() { 
        console.log('api call'); 
    }, 500))(); 

});


回答3:

Just calling throttle does nothing, you need to return the function as a function to the click handler:

$('.thing').click((function() { 
    console.log('hello!'); 

    return throttle(function() { 
        console.log('api call'); 
    }, 300); 

}()));