Remy Sharp's function throttler

空扰寡人 提交于 2019-12-13 06:21:36

问题


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); 

}()));


来源:https://stackoverflow.com/questions/7804312/remy-sharps-function-throttler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!