Last active
March 4, 2020 23:39
-
-
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(…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! (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); |
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
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: