javascript - 推入数组并循环,直到数组长度达到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()
解决方案
您需要将间隔保存到一个变量中,然后您可以使用该变量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);
推荐阅读
- excel - VBA-如果列具有某些文本并将其粘贴到某个单元格区域中,则将数据传输到另一个工作表
- javascript - React——为什么循环状态更新先于递归状态更新?
- python - 带有标头的 post API 的蝗虫基准测试
- c# - 使用 xunit 运行测试时,OpenCover 会抛出缺少的程序集异常
- php - 使用方法的返回值作为另一个对象的属性名
- r - 使用预定义参数模拟混合效应模型的数据
- git - 如何在使用 Visual Studio 在 git 中恢复提交后重新提交代码
- postgresql - 如何使用 Fluent 从 Vapor 3 中的同一个表中进行两个 JOIN 查询?
- opencv - 在 OpenCV 中使用 GPU
- keycloak - greenmail - keycloak connection doesn't work