问题描述
我正在尝试将一个值推入数组,直到达到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()
解决方法
您需要将时间间隔保存到一个变量中,然后可以在其上使用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);
,
我不确定我是否理解您的目的,因为那里有很多注释的代码,但是如果您要运行一次函数三次,然后以新的价格再运行一次,或者...可能是这样代码可以帮助您:
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);