Created
May 2, 2018 02:49
-
-
Save phobal/5d25abd96522f92d5f2979f111acad37 to your computer and use it in GitHub Desktop.
closure - 2种实现
This file contains hidden or 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
| function getStatus() { | |
| const random = Math.random() * 10 | |
| if (random > 5) { | |
| return true | |
| } else { | |
| return false | |
| } | |
| } | |
| function callback() { | |
| console.log('执行完毕') | |
| } | |
| function poll(getStatus, callback) { | |
| let time = 1000 | |
| return function del() { | |
| if (getStatus()) { | |
| console.log('getStatus执行了') | |
| setTimeout(() => { | |
| del() | |
| }, time) | |
| time *= 1.5 | |
| } else { | |
| callback() | |
| } | |
| } | |
| } | |
| poll(getStatus, callback)(); |
This file contains hidden or 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
| const callback = () => console.log('done'); | |
| const getStatus = () => !!Math.round(Math.random()); | |
| const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); | |
| function polling(getStatus, callback) { | |
| let delta = 1000; | |
| let start; | |
| return async function idle() { | |
| if (getStatus()) { | |
| console.log('idle'); | |
| await delay(delta); | |
| delta *= 1.5; | |
| return idle(); | |
| } | |
| return callback(); | |
| }; | |
| } | |
| polling(getStatus, callback)() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment