Throttle a function

by Josh Carroll

HTML

<input id='myInput' type='text'></input>

JavaScript

(function() {

    function throttle(func, timeout){
        var id = 0;
        return function(){
            var that = this,
                args = arguments;
            
            clearTimeout(id);
            
            id = setTimeout(function(){
                func.apply(that, args);
            }, timeout);
        };
    }
    
    $('#myInput').on('keypress', throttle(function(){ alert('woo hoo'); }, 500));
    
}());