记录一下,可选时间,间隔的轮询方法

53 阅读1分钟

记录一下,方便以后工作使用直接CV。

function runIntervalFunctionWithTimeout(totalTime, interval, params,callback) {
	let num = 0;
	const endTime = Date.now() + totalTime;
	let  isOn = true; //true继续,false停止
	const operateMap = {
		1: "测试成功",
		2: "扫码成功",
		3: "例子成功",
		4: "完全成功"
	}
	const msg = operateMap[params.type];
	async function  runInterval() {
	  if (Date.now() < endTime&&isOn) {
		num++;
		if(num>0&num%100===0) {
			interval+=1000;
		}
		doSomething(params).then(res=>{
			if(res.code===600){//成功执行成功callback
				isOn = false;
				if(callback){
					callback&&callback();
				}else{
					console.log(msg);
				}
			}
			if(res.code===604){//未完成继续轮询
				isOn = true;
			}
			if(res.code===724){//失败执行失败callback
				isOn = false;
				if(callback){
					callback&&callback(res);
				}
			}
		}).catch(err=>{
			isOn = false;
		})
		setTimeout(runInterval, interval);
	  }
	}
	runInterval();
}