Skip to content

Instantly share code, notes, and snippets.

@Krinkle
Last active March 7, 2019 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Krinkle/a9ec69e08538e85df1b11a8fee872e02 to your computer and use it in GitHub Desktop.
Save Krinkle/a9ec69e08538e85df1b11a8fee872e02 to your computer and use it in GitHub Desktop.
/*! Author: Timo Tijhof (2019) | License: Public domain. */
/**
* Wrap the function and debounce calls to it for a specified duration.
*
* @param {Number} delay
* @param {Function} callback
* @return {Function}
*/
function debounce( delay, callback ) {
var timeout;
return function debounced() {
clearTimeout( timeout );
timeout = setTimeout( Function.prototype.apply.bind( callback, this, arguments ), delay );
};
}
/**
* Make the function async and ignore successive calls until it's finished.
*
* @param {Function} callback
* @return {Function}
*/
function throttle( callback ) {
var pending, ctx, args;
return function() {
ctx = this, args = arguments; // last call before timeout should win
if ( !pending ) {
pending = setTimeout( function () {
pending = null;
callback.apply( ctx, args );
} );
}
};
}
@Krinkle
Copy link
Author

Krinkle commented Mar 7, 2019

$ php maintenance/minify.php debounce.js 
debounce.js -> debounce.min.js... ok
$ wc -c debounce.min.js 
180 bytes  debounce.min.js
$ cat debounce.min.js  | gzip -9 | wc -c
141 bytes

$ curl 'https://en.wikipedia.org/w/load.php?modules=ext.popups.main' > popups.min.js
$ wc -c popups.min.js 
57076 bytes  popups.min.js
$ cat popups.min.js | gzip -9 | wc -c
15996 bytes

$ cat debounce.min.js popups.min.js | gzip -9 | wc -c
16060

$ curl https://en.wikipedia.org/w/load.php?modules=jquery.throttle-debounce > jqthrotbounce.min.js
$ cat jqthrotbounce.min.js popups.min.js | gzip -9 | wc -c
16476

Net costs for module responses:

  • debounce: 64 bytes (16060 - 15996)
  • jquery.throttle-debounce: 480 bytes (16476 - 15996)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment