Question

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)

Was it helpful?

Solution

I have never used Ben's plugin, but it looks like the throttle plugin doesn't fire the function it returns a new function that can only be fired x times per second (or whatever). This works because in JS functions are first-class Objects, so a function can just return a new function.

so if you want the function to fire you need to call it,

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

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

you can also re-factor your first example like

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

 $(window).scroll(throttlesFunc);

internally jquery takes your passed in function reference and when the scroll event fires it does throttlesFunc(event)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top