背景:需要监听弹出窗口的关闭操作,然后开始发送请求,超过指定请求次数关闭定时器。
1. 设定一个变量记录请求次数
注意:每次请求前请求次数需要归0
2. 监听window.open()的关闭事件
注意:为了避免重复开启监听,当监听器为空时才开启监听
// 打开新页面
const winURL = window.open(finalUrl, "_blank", "top=200,left=700,width=600, height=700");
let loop = null;
if (!loop) {
loop = setInterval(() => { // 使用定时器查询当前状态
if (winURL && winURL.closed) { // 进行判断条件 closed属性就是返回当前窗口的状态
clearInterval(loop); // 清除定时器
console.log('监听结束,准备发起请求');
// 定时器次数归零,重新开启定时器
this.countTimer = 0;
this.getSetTimer();
} else {
console.log('监听窗口中');
}
}, 500);
}
3. 定时器方法
getSetTimer() {
this.interval = setInterval(()=> {
this.countTimer += 1;
if (this.countTimer === 5) {
this.clearTimer();
}
this.listFetch();
}, 2 * 1000);
},
clearTimer() {
clearInterval(this.interval);
this.interval = null;
},
本文介绍如何通过JavaScript监听浏览器新打开窗口的关闭事件,并在此基础上实现定时任务的启动与停止,确保在达到预设的请求次数后能够及时终止定时器。
1299

被折叠的 条评论
为什么被折叠?



