By Noxxxx from https://www.noxxxx.com/?post_type=post&p=541
欢迎分享与聚合,尊重版权,可以联系授权
1. 创建一个函数poll,它接受两个参数checkStatus[函数],callback[函数]。
2. poll会调用checkStatus,checkStatus返回true或者false。
3. 如果checkStatus返回true,调用callback并结束
4. 如果checkStatus返回false,1.5秒后继续调用checkStatus,如果还是返回false,1.5×2秒后继续调用checkStatus,还是false的话,1.5×3秒后继续调用,以此类推。
5. 不可以使用全局变量。
function poll(checkStatus, callback){ let time = 0; let timer = null; function dd(){ console.log(date()) let status = checkStatus(); if(status){ clearTimeout(timer); return callback(); } time++; timer = setTimeout(()=>{ dd(checkStatus, callback); }, time * 1500); } return dd; } function a(){return Math.random()>0.5} function b(){console.log('over')} function date(){ let d = new Date(); return `${d.getMinutes()}:${d.getSeconds()}` } poll(a,b)();