Created
May 6, 2018 14:56
-
-
Save lucarin91/915e255ebb282aae94c01cdd52ae5111 to your computer and use it in GitHub Desktop.
A simple JavaScript implementation of sleep using the yield command.
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
/* jshint esversion:6 */ | |
function * main (){ | |
console.log('Every time you need a sleep, you can yield the number of seconds that you want to wait..'); | |
yield 5; | |
console.log('..this will be executed 5 seconds later'); | |
yield 1.5; | |
console.log('[long wait]'); | |
yield 10; | |
console.log('..and, this after 10 seconds.\n'); | |
for (let i=0;i<5;i++){ | |
console.log('Have fun!'); | |
yield 1; | |
} | |
} | |
execute_with_sleep(main); | |
/** LIBRARY CODE */ | |
function execute_with_sleep(f){ | |
let gen = f(); | |
(function execute_rec(gen){ | |
let out = gen.next(); | |
if (!out.done && | |
!isNaN(parseFloat(out.value)) && isFinite(out.value)){ | |
setTimeout(() => { | |
execute_rec(gen); | |
}, out.value*1000); | |
} | |
})(gen); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment