Skip to content

Instantly share code, notes, and snippets.

@sina42048
Last active December 20, 2020 14:02
Show Gist options
  • Save sina42048/1e25e8eb7d98fdb37aacee2694245434 to your computer and use it in GitHub Desktop.
Save sina42048/1e25e8eb7d98fdb37aacee2694245434 to your computer and use it in GitHub Desktop.
simple generator function runner with requestAnimationFrame in javascript !
let sampleGenerator = function*() {};
let noop = () => {};
function *sleep(timer) {
return new Promise((res, rej) => {
setTimeout(() => {
res();
}, timer);
});
}
function *fetchData(url) {
return new Promise((res, rej) => {
fetch(url).then((data) => res(data));
});
}
function runMe() {
console.log('Run !');
}
function *test() {
yield runMe;
yield sleep(5000);
yield fetchData('https://jsonplaceholder.typicode.com/todos/1');
yield sleep(2000);
yield runMe;
yield sleep(8000);
yield fetchData('https://jsonplaceholder.typicode.com/posts/1');
}
function genRunner(genFunc) {
const userGeneratorFunction = genFunc();
let nextYield = userGeneratorFunction.next();
let inPromise = false;
let requestId;
return function runner(){
if (!inPromise && !nextYield.done) {
if (nextYield.value.constructor == noop.constructor) {
nextYield.value();
}
if (nextYield.value.constructor == sampleGenerator.prototype.constructor) {
nextYield = nextYield.value.next();
}
if (nextYield.value instanceof Promise) {
inPromise = true;
if (requestId) {
cancelAnimationFrame(requestId);
requestId = void 0;
}
nextYield.value.then((data) => {
if (data) console.log(data);
if (!nextYield.done) {
inPromise = false;
requestId = window.requestAnimationFrame(runner);
}
});
}
nextYield = userGeneratorFunction.next();
}
if (!nextYield.done && !inPromise) {
if (requestId) {
cancelAnimationFrame(requestId);
requestId = void 0;
}
requestId = window.requestAnimationFrame(runner);
}
}
}
const testRunner = genRunner(test);
testRunner();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment