gpt4 book ai didi

满足条件后 JavaScript 超时

转载 作者:行者123 更新时间:2023-12-02 17:22:59 25 4
gpt4 key购买 nike

我有一个条件,一旦满足,我想使该函数超时,这样在 X 时间内就不会再次调用它。在该时间段之后,如果满足条件,则可以再次调用。我怎样才能实现这个目标?

    setTimeout(function captureTimeout() {
console.log("CheckingScore");
if (ctrack.getScore() >= 0.8){
console.log("Capturing Data") ;

setTimeout(captureTimeout(), 30000);

}
}, 1000);

captureTimeout();

相当肯定上面的代码是极其错误的!

@JLRishe

我得到的 ctrack.getScore() 分数范围为 0.0 - 1.0,如果该值达到 0.8 或以上,我想执行一个函数来捕获当时页面的元素(正在寻找解决方案)这个),但现在我只想发出警报或用消息记录控制台。执行后,我希望在该函数再次执行之前有 30 秒的“冷却”期,因此即使 ctrack.getScore() 达到 0.8 或更高,我也只希望该函数在冷却完成后并且满足条件时执行冷却期结束后再次。希望这能解释得更多一点?

最佳答案

我很确定您想要完成的任务与setTimeout无关。

基本上,您需要在这里做的是跟踪冷却时间何时结束,或者:

  • 使用 if 语句跳过调用函数的代码,直到冷却时间结束或
  • 将逻辑放入函数中,以防止其在冷却期结束之前执行任何操作

我更喜欢第二个选项,因为无论谁尝试调用该函数,它都适用,以下是执行此操作的方法:

var coolDownSeconds = 30,
nextAllowedCapture = new Date();

function capturePage() {
var now = new Date();

if (nextAllowedCapture <= now) {
// Do capture logic
console.log("Capturing...");

nextAllowedCapture = new Date();
nextAllowedCapture.setSeconds(nextAllowedCapture.getSeconds() +
coolDownSeconds);
} else {
console.log("Can't capture again yet. This function can be executed again in " +
(nextAllowedCapture.getTime() - now.getTime()) / 1000 +
" seconds.");
}
}

http://jsfiddle.net/3U7Ud/2/

关于满足条件后 JavaScript 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23745126/

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