Skip to content

Instantly share code, notes, and snippets.

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 gagan-bansal/aa35aa5d5d239d903914fe44c5b761a7 to your computer and use it in GitHub Desktop.
Save gagan-bansal/aa35aa5d5d239d903914fe44c5b761a7 to your computer and use it in GitHub Desktop.
1) example 2) decelerating: callback is called at exponential rate, till max maximum delay is reached. 3) decelerating: callback is called at exponential rate if test satisfies, till max maximum delay is reached.
// source from https://stackoverflow.com/a/7445863/713573
function decelerating (callback, opts= {}) {
const {initialDelay = 100, exp = 2, maxDelay = 10000, test} = opts;
const myFunction = function() {
console.log('[debug] time: %s, delay: %s', Date.now(), delay);
if (test()) {
callback();
delay *= exp;
if (delay > maxDelay) {
delay = initialDelay;
}
} else {
delay = initialDelay;
}
setTimeout(myFunction, delay);
}
let delay = initialDelay;
setTimeout(myFunction, delay);
};
// function to test the condition if to start delcaration
function testFunc () {
return errStarted;
}
let errStarted = false;
decelerating (
() => console.log('called'),
{test: testFunc}
);
setTimeout(() => {
errStarted = true;
}, 2000);
setTimeout(() => {
errStarted = false;
}, 20000);
// source from https://stackoverflow.com/a/7445863/713573
function decelerating (callback, opts= {}) {
const {initialDelay = 10, exp = 2, maxDelay = 10000} = opts;
const myFunction = function() {
console.log('[debug] time: %s, delay: %s', Date.now(), delay);
callback();
delay *= exp;
if (delay > maxDelay) {
delay = initialDelay;
}
setTimeout(myFunction, delay);
}
let delay = initialDelay;
setTimeout(myFunction, delay);
}
decelerating (() => console.log('called'))
// source from https://stackoverflow.com/a/7445863/713573
const initialDelay = 5;
const exp = 2;
const maxDelay = 4000;
const myFunction = function() {
console.log('time: %s, delay: %s', Date.now(), delay);
delay *= exp;
if (delay > maxDelay) {
delay = initialDelay;
}
setTimeout(myFunction, delay);
}
let delay = initialDelay;
setTimeout(myFunction, delay);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment