Debounce with leader

Debounce function with optional leader argument; function passed to leader will execute at the beginning of the debounce

by chadarsenault

HTML

<div class="box">
    <span class="leader"></span>
    <span class="debounced"></span>
</div>

CSS

.box {
    box-sizing: border-box;
    width: 200px;
    height: 200px;
    background: #bada55;
    color: white;
    position: relative;
}

.leader {
    position: absolute;
    top: 20px;
    left: 20px;
}

.debounced {
    position: absolute;
    bottom: 20px; 
    right: 20px;
}
}

JavaScript

/*
* David Walsh's debounce function with optional leader argument; function passed to leader 
* will execute with every call and ignore debounce
* http://davidwalsh.name/javascript-debounce-function
* debounce( function func, int wait, bool immediate, function leader )
* func():    Function you want to debounce
* wait:      Time to wait in milliseconds
* immediate: If true, executes function at leading edge of wait
* leader:      Function to be executed with each call, ignoring debounce
*/

var debounce = function(func, wait, immediate, leader) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) {
				func.apply(context, args);
			}
		};

		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) {
			func.apply(context, args);
		}

		if (leader) {
			leader.apply(context, args);
		}
	};
};

$('.box').on('mousemove', debounce(function(e) {
        $('.debounced').html(e.pageX, e.pageY);    
    },
    250,
    false,
    function(e) {
        $('.leader').html(e.pageX, e.pageY);
    }
));