Remy Sharp的功能节流器 [英] Remy Sharp's function throttler

查看:114
本文介绍了Remy Sharp的功能节流器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用由Remy Sharp创建的限制功能( http:// remysharp.com/2010/07/21/throttling-function-calls/ )...它在标准使用中工作如此:

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

这很漂亮,但我想要能够在一个函数中调用特定部分的代码,而不是整个点击事件,像这样:

  $('。thing')。 .log('hello!'); 

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

});

但我不太明白为什么它不工作。油门代码返回一个函数,所以如果我用 .apply(this,arguments); 继续进行油门调用,然后键入'hello',函数被调用5次而不是一次因为节流功能内的定时器没有被覆盖。



通过jQuery点击代码筛选,但是真的找不到任何东西。我猜,jQuery创建了一个实例,然后回忆同一个实例,所以同样的计时器在那里?



有人理解这一点,为什么会发生这样? / p>

感谢,Dom

解决方案



以下是jsbin的解决方案: http:// jsbin .com / elabul / edit



throttle 方法返回 a函数将调节它的调用次数。所以你需要捕获一个变量中的坏男孩,并从它的点击处理程序中调用它:

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


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


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

解决方案

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

这篇关于Remy Sharp的功能节流器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆