News for hackers. Stuff that matters.
Re:Learning from Twitter by dionidium on Thursday January 20, 2011 @05:34PM (#2125596)
I use a generic version of the waiting-for-pause trick:

    // execute callback only after a pause in user input; the function returned
    // can be used to handle an event type that tightly repeats (such as typing
    // or scrolling events); it will execute the callback only if the given timout
    // period has passed since the last time the same event fired
    function createOnPause(callback, timeout, _this) {
        return function(e) {
            var _that = this;
            if (arguments.callee.timer)
                clearTimeout(arguments.callee.timer);
            arguments.callee.timer = setTimeout(function() { 
                callback.call(_this || _that, e);
            }, timeout);
        }
    }
Use it like this:

    document.addEventListener('scroll', createOnPause(function(e) {
        // do something interesting here
    }, 1500, this), false);
Edit: Oops! The version in the article runs some code if any scroll event occurred since it last fired, but this one doesn't execute the callback until the user stops scrolling for some amount of time. Anyway, maybe it's still useful for some folks.
Re:Learning from Twitter by long on Friday January 21, 2011 @03:47AM (#2126887)
For anyone that's interested, two related techniques are called "throttling" and "debouncing".
Re:Learning from Twitter by ryankirkman on Friday January 21, 2011 @04:59AM (#2126976)
Both of which are available in the awesome Underscore.js library: http://documentcloud.github.com/underscore/
Re:Learning from Twitter by mcav on Thursday January 20, 2011 @07:13PM (#2125879)
I've used that idiom too. It's a great trick. One potential issue is that if you continuously trigger the scroll/resize event, your callback will go an extended time without firing. That's usually only a problem if you're using it to adjust UI elements on scroll/resize, in which case you'd want to add a timer to force the callback if the delay has been too long despite the event still firing often.