首页 > 解决方案 > 推入数组并循环,直到数组长度达到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()

标签: javascriptarraysloopspushsettimeout

解决方案


您需要将间隔保存到一个变量中,然后您可以使用该变量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);


推荐阅读