雷米夏普的功能节流阀
尝试使用 Remy Sharp 创建的节流函数 (http://remysharp. com/2010/07/21/throttle-function-calls/)...它在标准使用中工作,如下所示:
$('.thing').click(throttle(function() {
console.log('api call');
}, 300);
这非常简洁,但我希望能够限制函数中代码的特定部分,而不是整个点击事件,如下所示:
$('.thing').click(function() {
console.log('hello!');
throttle(function() {
console.log('api call');
}, 300);
});
但我不太明白为什么它不起作用。节流代码返回一个函数,因此如果我使用 .apply(this, Arguments);
继续节流调用,然后输入“hello”,该函数将被调用 5 次,而不是作为节流中的计时器调用一次函数没有被覆盖。
筛选了 jQuery 点击代码,但找不到任何东西。我猜 jQuery 创建了它的一个实例,然后调用同一个实例,所以有相同的计时器吗?
有谁理解这一点以及为什么会这样?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你做错了;-)
这是 jsbin 上的解决方案: http://jsbin.com/elabul/edit< /a>
throttle
方法返回一个函数,该函数将限制其调用次数。因此,您需要在变量中捕获那个坏男孩并从单击处理程序内部调用它,如下所示: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:您需要调用从节流函数返回的:
you need to call returned from throttle function:
仅调用throttle 不会执行任何操作,您需要将函数作为函数返回给单击处理程序:
Just calling throttle does nothing, you need to return the function as a function to the click handler: