debounce resize/mousemove

jQuery resize and tracking use movement with mousemove is useful, but it fires so many events. Every pixel you are making an event call. With debounce, you can call essentially rate limit this and only call when user has stopped resizing for N milliseconds

by Augustus Yuan

HTML

<div>Number of times run debounce: <span class="debounce">0</span></div>
<div>Mouse coordinates: <br/><span class="debounce-coords"></span></div>

<br />

<div>Number of times run without debounce: <span class="jquery">0</span></div>
<div>Without Debounce Mouse coordinates: <br/><span class="jquery-coords"></span></div>

CSS

.debounce {
    color: red;
}

.jquery {
    color: green;
}

JavaScript

// TODO: handle screen sizing

var doit;
function mousemovedw(e, classTimes, classCoords){
    var num = parseInt($(classTimes)[0].innerHTML) + 1;
    var coords = '[' + e.pageX + ', ' + e.pageY + ']';
    $(classTimes).text(num);
    var existingCoords = $(classCoords).text();
    var appendCoords = existingCoords === '' ? coords : existingCoords + ', ' + coords;
    $(classCoords).text(appendCoords);
}
window.onmousemove = function(e) {
    clearTimeout(doit);
    doit = setTimeout(function() {
        mousemovedw(e, '.debounce', '.debounce-coords');
    }, 100, e);
};

$(window).mousemove(function(e) {
	mousemovedw(e, '.jquery', '.jquery-coords');
});