javascript高级编程系列 - web前端中如何中断程序,等待条件满足时再返回继续执行代码?

1. 使用 async/await 配合 Promise(推荐)

  • 封装一个等待条件满足的执行函数,通过异步等待机制实现 "暂停" 效果
/***
* conditionCheck: 条件检测函数
* interval: 检测间隔时间,默认100ms
* timeout: 设置超时时间, 默认5s
*/
async watchSeverSelect(conditionCheck, interval = 100, timeOut = 5000) {
  const beginStamp = _.now(); // 初始化监测开始时间
  
  return new Promise((resolve, reject) => {
	// 创建一个定时器,定期检查条件
	const checkInterval = setInterval(() => {
	  if (conditionCheck()) {
		clearInterval(checkInterval); // 条件满足,清除定时器
		resolve(this.currentServer); // 结束等待,返回一个指定的数据
	  } else {
		// 取消选择场景,如果检测值为一个特殊值则,清除定时器,promise 返回reject的信息。
		if (this.currentServer === 0) {
		  clearInterval(checkInterval); // 清除定时器
		  reject("未选择可用服务,请重新登录!");
		}
		
		// todo 考虑超时场景
		const time = _.now() - beginStamp;
		if (time > timeOut) {
		  clearInterval(checkInterval); // 清除定时器
		  reject("选择可用服务超时,请重新登录!");
		}
	  }
	}, interval);
  });
}
  • 在等待条件满足函数执行期间,执行下面的两个函数,改变监测的值
// 确认选择
confirmSelect(e) {
  console.log(e);
  // 设置选中的系统服务
  this.currentServer = e[0];
},
// 取消选择
cancelSelect(e) {
  console.log("cancel", e);
  this.currentServer = 0; //0 表示取消选择
},
  • 执行条件监测函数,检查条件为this.currentServer的值不为null 和 0,时成功返回,否则失败。
const serverItem = await this.watchSeverSelect(
  () => this.currentServer
);

2. 简单场景直接使用定时器轮询

console.log("程序开始执行");

let flag = false;
// 模拟3秒后条件变为true
setTimeout(() => { flag = true; }, 3000);

console.log("等待条件满足...");

// 轮询检查条件
const checkInterval = setInterval(() => {
  if (flag === true) {
    clearInterval(checkInterval); // 清除定时器
    console.log("条件已满足,继续执行后续代码");
	
    // 这里写后续需要执行的逻辑
  }
}, 100); // 每100ms检查一次

3. while(true){} 语句会阻碍主线程导致UI卡死,不建议使用。

posted @ 2025-08-15 11:34  箫笛  阅读(20)  评论(0)    收藏  举报