简体   繁体   English

javascript setTimeout() 几分钟后不起作用,然后立即解决

[英]javascript setTimeout() is not working after few minutes and then it resolves without delay

I wrote a code for timer of 60 seconds but setTimeout() is executing properly for few minutes but after some time it is resolving the function but without delay and the function is getting resolved in each second.我为 60 秒的计时器编写了一个代码,但 setTimeout() 可以正常执行几分钟,但一段时间后它正在解决 function 但没有延迟,并且 function 每秒都得到解决。

Here, this.rateCardTimerText is init with zero in the first call.在这里, this.rateCardTimerText 在第一次调用中初始化为零。

Please provide any proper solution if available or is there any alternative way to achieve it then please also mention that.如果可用,请提供任何适当的解决方案,或者是否有任何替代方法来实现它,然后请提及。

onChangeTimerChangeInfinity() {

    let no = Number(this.rateCardTimerText)

    if (no >= 100) {
        no = 0
        this.getCurrencyList()
    }
    else {
        no += 1.66
    }

    this.rateCardTimerText = no
    this.forceUpdate()
    setTimeout(this.onChangeTimerChangeInfinity.bind(this), 1000)
}

Make sure you clear out the previous setTimeout each time you run it, like so:确保在每次运行时清除之前的 setTimeout,如下所示:

let intervalObj;

onChangeTimerChangeInfinity() {
    clearTimeout(intervalObj)
    let no = Number(this.rateCardTimerText)

    if (no >= 100) {
        no = 0
        this.getCurrencyList()
    }
    else {
        no += 1.66
    }

    this.rateCardTimerText = no
    this.forceUpdate()
    intervalObj = setTimeout(this.onChangeTimerChangeInfinity.bind(this), 1000)
}

Also, just as with the above setInterval() option, you may end up with code tripping over itself because you're forcing this thing to fire every second regardless.此外,就像上面的setInterval()选项一样,您最终可能会导致代码自己跳闸,因为无论如何您都在强制这个东西每秒触发一次。 If getCurrencyList() or forceUpdate() are async , consider rewriting a second function as a promise, then something like:如果getCurrencyList()forceUpdate()async ,请考虑将第二个 function 重写为 promise,然后类似于:

let intervalObj;

onChangeTimerChangeInfinity() {
    clearTimeout(intervalObj)
    doAsyncStuffInPromise().then( () => {
       intervalObj = setTimeout(this.onChangeTimerChangeInfinity.bind(this), 1000)
    })
    
}

Use setInterval() instead.请改用setInterval()

setInterval( () => onChangeTimerChangeInfinity, 1000);

onChangeTimerChangeInfinity() {

    let no = Number(this.rateCardTimerText);

    if (no >= 100) {
        no = 0;
        this.getCurrencyList();
    }
    else {
        no += 1.66;
    }

    this.rateCardTimerText = no;
    this.forceUpdate();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM