为何setTimeout始终未执行?无论是否调用clearTimeout
为什么setTimeout的重定向代码始终不执行?
我设置了一个10秒后执行重定向的setTimeout,但对应的代码块从未运行,控制台也没有输出"redirecting"。相关代码及控制台输出如下:
第一段主代码
window.onbeforeunload = null; // this part is never executing this.timeout = setTimeout(function(){ console.log("redirecting"); location.href="/dashboard"; }, 10000); try { // here I also call the other function await this.recorder.stop(); } catch (err) { console.log(err); clearTimeout(this.timeout); }
this.recorder.stop()的实现代码
console.log("sending mail"); var self = this; // console.log(blob instanceof Blob); var file = new File([blob], "recording"); var formData = new FormData(); formData.append("recording", file); formData.append("format", (this.isIOS ? "mp4" : "webm")); formData.append("routine_id", this.routine_id); axios.post('/room/send/recording', formData) .then(function (response) { if(response.data.result) { console.log("email has been sent") } else { console.log("failed to send email") } }) .catch(({response}) => { console.log("an error occured during email call") console.error(response); }) .finally(function() { clearTimeout(self.timeout); console.log("timeout cleared"); });
控制台输出
sending mail email has been sent timeout cleared
核心原因
你的axios请求在10秒内就完成了,触发了finally块里的clearTimeout(self.timeout),直接把定时器提前清除了,所以定时器的回调函数永远不会执行。
从控制台输出能看到,整个请求流程(发送请求→成功响应→进入finally)耗时远小于10秒,此时定时器还没到触发时间就被销毁,自然不会执行console.log("redirecting")和重定向逻辑。另外self.timeout和主代码里的this.timeout指向同一个定时器实例,所以清除操作会直接让定时器失效。
可选调整方向
- 仅在请求成功时清除定时器:把
clearTimeout移到then块内,失败时保留定时器触发重定向; - 无论请求结果都执行重定向:移除
finally里的clearTimeout,只在catch中按需清除; - 请求完成后立刻重定向:直接在
finally块里调用重定向逻辑,去掉定时器。
内容的提问来源于stack exchange,提问作者The Blind Hawk
相关产品推荐
相关产品推荐

