Underscore - Debounce and Throttle Example

Underscore - Debounce and Throttle Example

by Nirvanachain

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>

JavaScript

// Find size of window.
var calcSize = function () {
    var width = this.innerWidth;
    var height = this.innerHeight;
    console.log('debounced width =', width);
    console.log('debounced heightheight =', height);
};

// Find size of window.
var findWindowSize = function () {
    var width = this.innerWidth;
    var height = this.innerHeight;
    console.log('throttle width =', width);
    console.log('thottle heightheight =', height);
};

// Pass calcSize function to debounce.  Fire calcSize 1 second after 
// event has finished.
var debounceCalcSize = _.debounce(calcSize, 1000);

// Fire the debounced function 1000 second after the
// window is finished resizing
$(window).resize(debounceCalcSize);

var throttleFindWindowSize = _.throttle(findWindowSize, 1000);
$(window).resize(throttleFindWindowSize);