Skip to content

Instantly share code, notes, and snippets.

@phobal
Created May 2, 2018 02:49
Show Gist options
  • Select an option

  • Save phobal/5d25abd96522f92d5f2979f111acad37 to your computer and use it in GitHub Desktop.

Select an option

Save phobal/5d25abd96522f92d5f2979f111acad37 to your computer and use it in GitHub Desktop.
closure - 2种实现
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)();
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