Underscore _.debounce() : How to execute method only the last time received?

javascript, underscore.js

Solution

After reading your comment, this is clearer now.

well perhaps it's my browser (infrequent resize events, causing _debounce to be called? testing on Chrome), but while resizing, I keep getting multiple calls to the body of the debounced function. As if it's behaving exactly as _.throttle now I come to think of it.. Weird stuff.

50ms is a pretty low debounce time. I'm betting it was working as intended, and you just need a longer debounce time. 50ms is 1/20th of a second. I'm not sure the window resize event fires that quickly. But even if it does, the tiniest pause in mouse movement while resizing could triggers this.

Remove all this `setTimeout` nonsense in your debounced function and set the debounce time to something more like `250` and I bet it will work just like you want.

Problem

`_.debounce()` fires at most evevry x milliseconds with `_.debounce(function,x`) .. I want to adapt this to only execute a method `x` millis after the last `_.debounce()`. How do I go about this? (I've read that `$.debounce` does exactly that btw.) I've tried to do this, but it isn't bullet-proof (not to mention butt-ugly) ``` var timeout; $(window).on("resize",_.debounce(function(){ if(timeout){ clearTimeout(timeout); } //when debounce comes in we cancel it.. this means only the latest debounce actually fires. //not bullet proof timeout = setTimeout(resizeMap,100); },50)); ``` How to do this elegantly?

Original source