嵌套 setInterval javascript

Nested setInterval javascript

我有这样的JS代码

function Entry(){
  var Trigger = setInterval(function () {
      var ent = EntryZone(); //EntryZone is a function which returns a value that change in every second
      if (Value <= ent) { // Value is a variable
        clearInterval(Trigger); 
        var TakeEntry = setInterval(function () {
          var chkPer = Percentage(); //Percentage() is a function which returns a value that change in every second
            if (Value >= chkPer) { //Here I am comparing Value with chkPer
              var interval = setInterval(function(){    
                if (Value >= chkPer){ //Here I want to compare Vlaue again with chkPer after 10 seconds. If it has still the same or grater value then proceeding further.
                  BuyNow();
                  clearInterval(TakeEntry);
                }
                clearInterval(interval);
              },10000);
            }
        }, 500);
      }
  }, 500);
}

好的,这就是我想要做的。但是当我 运行 脚本搞砸了。我想在 10 秒后再次检查值的中间部分正在执行多次。我只想执行一次。如果 10 秒后值不相同,则清除“间隔”间隔并返回并继续“TakeEntry”间隔。 请指导我代码有什么问题。谢谢!

我认为使用 setTimeout 而不是 setInterval 更容易正确编写此类代码。这就是我相信你从你的描述中得到的意思,但你可以轻松地将代码修改为例如在某些情况下再次触发 Entry。这个想法是,在任何时候,三个函数中至多一个应该有一个超时计划。

function Entry(){
  setTimeout(function () {
    var ent = EntryZone(); //EntryZone is a function which returns a value that change in every second
    if (Value <= ent) { // Value is a variable
      TakeEntry();
    } else {
      Entry();
    }
  }, 500);
}
function TakeEntry(){
  setTimeout(function () {
    var chkPer = Percentage(); //Percentage() is a function which returns a value that change in every second
    if (Value >= chkPer) { //Here I am comparing Value with chkPer
      Check10();
    } else {
      TakeEntry();
    }
  }, 500);
}
function Check10(){
  setTimeout(function(){    
    if (Value >= chkPer){ //Here I want to compare Value again with chkPer after 10 seconds. If it has still the same or grater value then proceeding further.
      BuyNow();
    } else {
      TakeEntry();
    }
  }, 10000);
}

问题是对 setInterval( ....., 10000) 的调用没有停止另一个间隔继续计时...

这种逻辑用async await语法更容易实现:

// Utility function to await a given delay:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function entry() {
    while (true) { // Keep doing?
        var ent = EntryZone();
        while (Value > ent) {
            await delay(500);
            ent = EntryZone();
        }
        while (true) {
            var chkPer = Percentage();
            if (Value >= chkPer) {
                await delay(10000);
                chkPer = Percentage();
                if (Value >= chkPer) {
                    BuyNow();
                    break;
                }
            }
            await delay(500);
        }
    }
}