throttle javascript functions or ajax functions

function throttle(func, wait) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        if (!timeout) {
            // the first time the event fires, we setup a timer, which 
            // is used as a guard to block subsequent calls; once the 
            // timer's handler fires, we reset it and create a new one
            timeout = setTimeout(function() {
                timeout = null;
                func.apply(context, args);
            }, wait);
        }
    }
}

//example
document.addEventListener("scroll", throttle(function() {
    console.log("test");
}, 2000), false);

http://stackoverflow.com/questions/5031501/how-to-rate-limit-ajax-requests

Leave a Reply

Your email address will not be published. Required fields are marked *