Last active
December 20, 2020 14:02
-
-
Save sina42048/1e25e8eb7d98fdb37aacee2694245434 to your computer and use it in GitHub Desktop.
simple generator function runner with requestAnimationFrame in javascript !
This file contains 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
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