jQuery throttle / debounce

http://benalman.com/projects/jquery-throttle-debounce-plugin/

by Ben Alman

HTML

<script src="http://benalman.com/code/projects/jquery-throttle-debounce/jquery.ba-throttle-debounce.js"></script>
<!-- An example for http://benalman.com/projects/jquery-throttle-debounce-plugin/ -->

<h1>An example for <a href=" http://benalman.com/projects/jquery-throttle-debounce-plugin/">jQuery throttle / debounce</a>.</h1>

<p>Resize this window or move the mouse over it.</p>

<div id="resize">Window is being resized...</div>
<div id="mousemove">Mouse is being moved...</div>

CSS

.resizing { background: #afa; }
.moving { background: #aaf; }

div {
    display: none;
    margin-top: 1em;
}

.resizing #resize,
.moving #mousemove {
    display: block;
}

JavaScript

var body = $('body');

$(window)
    .resize( $.debounce( 250, true, function(e){
        body.addClass( 'resizing' );
    }))
    .resize( $.debounce( 250, false, function(e){
        body.removeClass( 'resizing' );
    }));

$(document)
    .mousemove( $.debounce( 250, true, function(e){
        body.addClass( 'moving' );
    }))
    .mousemove( $.debounce( 250, false, function(e){
        body.removeClass( 'moving' );
    }));