推送数组并循环直到数组长度达到 3

我试图将数组推入一个值,直到它达到 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()


暮色呼如
浏览 141回答 2
2回答

有只小跳蛙

您需要将间隔保存到一个变量中,然后您可以在该变量clearInterval()上使用。这是您要完成的任务的模型。var array = [];var maxLength = 3;var delay = 250; //I shortened your delayvar ticker = {}; //I'll use this to simulate your ticker objectvar looper = setInterval(function() {&nbsp;&nbsp; &nbsp; &nbsp; ticker.BNBBTC = Math.random(); //populating your ticker property w/random value&nbsp; &nbsp; &nbsp; if (array.length < maxLength) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;array.push(ticker.BNBBTC);&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log("Stopping the looper.");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;clearInterval(looper);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log("Here are the contents of array");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(array);&nbsp; &nbsp; &nbsp; }}, delay);

青春有我

我不确定我是否理解你的目的,因为那里有很多注释代码,但如果你想运行一个函数三次并在一秒钟后以新价格再次运行它,或者......可能这段代码对你有帮助:let array = [];let eachEverySeconds = 1;const loopArray = (array) => {&nbsp; &nbsp; setTimeout(async () => {&nbsp; &nbsp; &nbsp; &nbsp; if (array.length === 3) return;&nbsp; &nbsp; &nbsp; &nbsp; let price = Math.random() * 10;&nbsp; &nbsp; &nbsp; &nbsp; array.push(price);&nbsp; &nbsp; &nbsp; &nbsp; await loopArray(array);&nbsp; &nbsp; }, 1000 * eachEverySeconds);&nbsp; &nbsp; console.log(array);};loopArray(array);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript