前端实现轮询
/** * * @param callback 需要轮询的函数 * @param interval 轮询的间隔时间 * @returns */ export function pollFn(callback, interval = 1000) { let timerId; //是否停止轮询 let isStop = false; //轮询请求 const pollFetch = async () => { await callback(); if (isStop) return; timerId = setTimeout(pollFetch, interval); return; }; //开始轮询 const start = async () => { await pollFetch(); }; //停止轮询 const stop = () => { isStop = true; clearTimeout(timerId); }; return { start, stop, }; }
//使用方法 mounted(){ this.pollManager = pollFn(this.pollQuery, 5000 ); //开始轮询 this.pollManager&&this.pollManager.start&&this.pollManager.start(); //7秒之后清楚轮询 setTimeout(()=>{
this.pollManager&&this.pollManager.stop&&this.pollManager.stop();
this.pollManager=null; },
7000) }
//http请求
async pollQuery(){
await new Promise((resolve, reject) => {
setTimeout(()=>{ resolve(true) },5000)
})
}