Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript function debounce and throttle
// Original code from Nathan Claire's blog
// http://nathanleclaire.com/blog/2013/11/16/the-javascript-question-i-bombed-in-an-interview-with-a-y-combinator-startup/
$(document).ready(function() {
$('input').keypress(function() {
if (this.timeoutId)
window.clearTimeout(this.timeoutId);
this.timeoutId = window.setTimeout(function () {
$.ajax({
// do some stuff
});
}, 200);
});
});
// Original code from Paul Irish's blog
// http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});
// Original code from
// http://www.hnldesign.nl/blog/debouncing-events-with-jquery/
var deBouncer = function($,cf,of, interval){
// deBouncer by hnldesign.nl
// based on code by Paul Irish and the original debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
}
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || interval);
};
};
jQuery.fn[cf] = function(fn){ return fn ? this.bind(of, debounce(fn)) : this.trigger(cf); };
};
//register debouncing functions
//deBouncer(jQuery,'new eventname', 'original event', timeout);
//Note: keep the jQuery namespace in mind, don't overwrite existing functions!
deBouncer(jQuery,'smartresize', 'resize', 100);
deBouncer(jQuery,'smartscroll', 'scroll', 100);
deBouncer(jQuery,'smartmousemove', 'mousemove', 100);

Difference between Debounce and Throttle

Debounce

Debounce a function when you want it to execute only once after a defined interval of time. If the event occurs multiple times within the interval, the interval is reset each time.
Example A user is typing into an input field and you want to execute a function, such as a call to the server, only when the user stops typing for a certain interval, such as 500ms.

Throttle

Throttle a function when you want it to execute periodically with an interval in between each execution.
Example A user is typing into a field continuously for 30s but you want to make sure you capture a users input every 1s and perform an action.

Reference

A good explanation with an even better visual aide can be found here.
Ben Alman of gruntjs fame, has a jQuery throttle/debounce lib, explantions here

@oleander

This comment has been minimized.

Copy link

oleander commented Jan 6, 2016

Awesome, thanks!

@maninak

This comment has been minimized.

Copy link

maninak commented Oct 15, 2017

Thank you! Would be awesome if you could include a (set of?) throttle implementations as well since I got here fro Google looking for that. Preferably implemented with vanilla js.

EDIT:
The following seems like a fine way to do it.

function throttle(func, msWait) {
  var time = Date.now();
  return function() {
    if ((time + (msWait || 100) - Date.now()) < 0) {
      func();
      time = Date.now();
    }
  }
}

Can be used as:

window.addEventListener('scroll', throttle(myOnScrollFunction), false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.