【问题标题】:Push array and loop until the array length reach 3推入数组并循环,直到数组长度达到3
【发布时间】:2021-01-28 03:22:15
【问题描述】:

我正在尝试向数组推送一个值,直到它达到 3 的长度。我还想为循环添加延迟。任何修复代码的建议。如果满足条件,则中断并转到下一个函数。非常感谢!

let array = [];
let eachEverySeconds = 1;
//function fetchCoinPrice(params) { //BinanceUS Fee: 0.00075 or 0.075%
function Firstloop() {
  for (x = 0; x < 4; x++) {

    setTimeout(function() {
      function fetchCoinPrice() {
        binance.prices(function(error, ticker) {
          //array.push(ticker.BNBBTC);    
          //while(array.length<3){


          //if (array.length<4){
          array.push(ticker.BNBBTC);
          console.log("1", array);
          //}else {}//if (array.length === 3) { break; }
          // array.shift();

        });
      }
    }, 1000)
  }
}
// setInterval(Firstloop, eachEverySeconds * 1000);
Firstloop()

【问题讨论】:

    标签: javascript arrays loops push settimeout


    【解决方案1】:

    您需要将间隔保存到一个变量中,然后您可以在该变量上使用clearInterval()

    这是您要完成的工作的模型。

    var array = [];
    var maxLength = 3;
    var delay = 250; //I shortened your delay
    var ticker = {}; //I'll use this to simulate your ticker object
    
    var looper = setInterval(function() { 
          ticker.BNBBTC = Math.random(); //populating your ticker property w/random value
    
          if (array.length < maxLength) {
             array.push(ticker.BNBBTC);
          } else {
             console.log("Stopping the looper.");
             clearInterval(looper);
             console.log("Here are the contents of array");
             console.log(array);
          }
    }, delay);

    【讨论】:

      【解决方案2】:

      我不确定我是否理解您的目的,因为那里有很多注释代码,但是如果您想运行一个函数三次并在一秒钟后以新价格再次运行它,或者......可能是这样代码可以帮助你:

      let array = [];
      let eachEverySeconds = 1;
      
      const loopArray = (array) => {
          setTimeout(async () => {
              if (array.length === 3) return;
              let price = Math.random() * 10;
              array.push(price);
              await loopArray(array);
          }, 1000 * eachEverySeconds);
          console.log(array);
      };
      
      loopArray(array);

      【讨论】:

      • 太棒了,我喜欢每个人都有自己的编程方式。感谢您的努力!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 2017-06-22
      • 2020-09-11
      • 2016-05-18
      • 2020-06-21
      • 1970-01-01
      相关资源
      最近更新 更多