JSFiddle - React, Tailwind, and code Playground
JavaScript
/**
* Class that will handle delayed function calls
* @param fn the funciton to call
* @param ctx the context to use as 'this' inside the function
* @param delay delay in millis
*/
var AsyncCall = function(fn, ctx, delay) {
var timer = null;
ctx = ctx || window;
delay = delay || 1;
return function() {
// prevent calling the delayed function multiple times
if (timer) clearTimeout(timer);
var args = arguments;
timer = setTimeout(function() {
timer = null;
fn.apply(ctx, args);
}, delay);
};
};
var test = AsyncCall(function() {
alert("ok is executed only once!");
});
for (var i=0; i<10; i++) {
test();
}
alert("done calling test() 10 times");