我正在编写一个片段,其中 JS 将数组的所有元素显示为计数器,在循环中的步骤海滩之间具有随机延迟。但是,clearInterval 和 setInterval 似乎不起作用,因为我观察到它永远在浏览器控制台中打印值。
这是代码
var low = Math.floor(Math.random() * (80 - 65 + 1)) + 65;
var high = Math.floor(Math.random() * (95 - low + 1)) + low;
// generate array between low to high
heartbeats = Array.from( {length: 15}, () => Math.floor(Math.random() * (high - low + 1)) + low );
// sort it
heartbeats = heartbeats.sort((a,b) => a - b);
for (i in heartbeats){
var randomPause = Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000;
theLooper = setInterval( function () {
if (i == (heartbeats.length - 1) ) clearInterval(theLooper);
console.log("Random Pause Is :: " + randomPause);
console.log(heartbeats[i]);
name1.innerHTML = heartbeats[i];
},randomPause);
}
我得到的不是计数器而是先低后高的打印,而不是打印数组中的所有元素。并且控制台日志永远保持高打印
最佳答案
问题:
事实上,在您的实际代码中,您不会在相应的延迟后一一打印数组的值,您只是在延迟过去后打印 banch 中的所有元素。
当您使用setInterval
时,显示不会停止,它将永远显示。
解决方案:
您需要在循环
中使用setTimeout
,而不是setInterval
,它会延迟指令一次,并确保递增setTimeout
函数根据迭代的 index
使用的延迟:
setTimeout(function() {
console.log("index: " + i + " & element: " + el);
}, i * 1000);
演示:
这是一个演示片段:
var low = Math.floor(Math.random() * (80 - 65 + 1)) + 65;
var high = Math.floor(Math.random() * (95 - low + 1)) + low;
// generate array between low to high
heartbeats = Array.from({
length: 15
}, () => Math.floor(Math.random() * (high - low + 1)) + low);
// sort it
heartbeats = heartbeats.sort((a, b) => a - b);
heartbeats.forEach(function(el, i) {
setTimeout(function() {
console.log("index: " + i + " & element: " + el);
}, i * 1000);
});
关于javascript - 如何使用 setInterval 和clearInterval 获得延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48687388/