Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active March 4, 2020 23:39
Show Gist options
  • Save WebReflection/7286687 to your computer and use it in GitHub Desktop.
Save WebReflection/7286687 to your computer and use it in GitHub Desktop.
whenever you need to execute something after an interaction that might happen many times (panning, scrolling, etc) … this simple mechanism makes simple to execute that maybe expensive operations only once when things are "quiet" and never before or in the middle, if an action start as "start panning" would be is fired and it's calling the clear(…
/*! (C) Andrea Giammarchi */
var Delayed = function(delay){
function Delayed(callback, delay) {
if (!delay) delay = Delayed.delay;
function delayed() {
clear();
delayed._ = setTimeout(
invoke, delay, callback, this, arguments, delayed
);
}
function clear() {
clearTimeout(delayed._);
}
delayed.clear = clear;
delayed._ = 0;
return delayed;
}
function clear() {
clearTimeout(this._);
this._ = 0;
return this;
}
function invoke(callback, context, args, delayed) {
delayed._ = 0;
callback.apply(context, args);
}
Delayed.delay = delay;
return Delayed;
}(500);
@WebReflection
Copy link
Author

few examples on how to in calendar.perfplanet.com

If you are targeting IE < 9 browser you might want to use this snippet to normalize setTimeout extra arguments:

/*@cc_on
(function(f){
 window.setTimeout =f(window.setTimeout);
 window.setInterval =f(window.setInterval);
})(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c.apply(this,a)},t)}});
@*/

@kentaromiura
Copy link

Apparently jshint get scared by a function referencing this outside an object,
solved by adding /*jshint validthis: true */
after clear() and delayed() method definition,
see https://gist.github.com/kentaromiura/7874867

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