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 */
// https://gist.github.com/WebReflection/7286687
var Delayed = function(delay){
function Delayed(callback, delay) {
function delayed() {
// ensure the right clear method
clear.call(delayed);
// re-set the timeout (still waiting after)
delayed.waiting = setTimeout(
invoke, delay, delayed, callback, this, arguments
);
}
if (!delay) delay = Delayed.delay;
// a ways to stop the execution
delayed.clear = clear;
// although waiting will be false only once executed
delayed.waiting = Infinity;
// **or** if explicitly blocked by a user
return delayed;
}
function clear() {
if (this.waiting !== Infinity) {
clearTimeout(this.waiting);
}
this.waiting = 0;
}
function invoke(delayed, callback, context, args) {
// mark as consumed already, not waiting anymore
delayed.waiting = 0;
// finally invoke the callback
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