gpt4 book ai didi

javascript - setTimeout 在 try/catch 中不起作用

转载 作者:行者123 更新时间:2023-12-03 02:20:42 25 4
gpt4 key购买 nike

我正在等待提供商更新 this.myprovider.SomeVarIsNotUndefined。我无法使用 Promise 让我的脚本等待,所以我想出了这个,但它似乎只运行一次。因此,当 this.myprovider.SomeVarIsNotUndefined = undefined 时,setTimeout() 不会在 catch 区域重新触发虽然 console.log(err) 正在触发。

someFunction(){

try {

if(this.myprovider.SomeVarIsNotUndefined){
//...
console.log("works");
}
}
catch(err) {

//if error then re-run after 0.5 seconds
setTimeout(() => { this.someFunction(); }, 500);
console.log(err);

}

}

//run func for the first time
this.someFunction();

最佳答案

下面的代码工作得很好,第一次变量是未定义的,程序流程进入catch block 。然后在 catch block 中,我定义了变量,然后设置超时函数重新触发该函数并给出 console.log - “works”

<script>

function someFunction(){
try {

if(SomeVarIsNotUndefined){
//...
console.log("works");
}
}
catch(err) {

//if error then re-run after 0.5 seconds
setTimeout(() => { SomeVarIsNotUndefined = 1; this.someFunction(); }, 500);
console.log(err);

}

}

//run func for the first time
this.someFunction();
</script>

https://www.w3schools.com/code/tryit.asp?filename=FP6TDP0ESYVW

关于javascript - setTimeout 在 try/catch 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49176003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com