0

I'm using Ben Alman's Throttle-debounce plugin.

When I call .throttle like that:

$(window).scroll($.throttle(250, function() {console.log(1)}));

throttled function fires.

But I have to check if scroll event isn't triggered. So when I do this

$(window).scroll( function(event) {
    if (!event.isTrigger) {
        $.throttle(250, function() {console.log(1)});
        console.log(2);
    }
});

I get only "2" in result. For some reason throttled function isn't fire. (the second console printing is to show, that code goes through throttled function)

4

1 回答 1

2

我从未使用过 Ben 的插件,但看起来油门插件不会触发它返回一个新函数的函数,该函数每秒只能触发 x 次(或其他)。这是有效的,因为在 JS 中函数是一等对象,所以一个函数可以只返回一个新函数。

所以如果你想让函数触发你需要调用它,

 var throttledFunc = $.throttle(250, function() {console.log(1)});

 $(window).scroll( function(event) {
    if (!event.isTrigger) {
       throttledFunc(event);
       console.log(2);
    }
  });

您还可以重构您的第一个示例,例如

 var throttledFunc = $.throttle(250, function() {console.log(1)});

 $(window).scroll(throttlesFunc);

jquery 在内部获取您传入的函数引用,并且当滚动事件触发它时throttlesFunc(event)

于 2013-11-06T15:47:45.787 回答