使用JsFiddle here,我需要每隔1s更改一个div的innerHTML,其中包含100个元素的数组中的值。我正在使用循环迭代数组的元素,然后使用setTimeout
每1000ms更新#number
的innerHTML。然而,我看到的是该元素在1000ms后立即更新。
let num = 100
let data = [];
for (let i = 0; i < num; i++) {
data.push(Math.random() * 100);
}
console.log(data);
function loadScript(){
console.log(`Calling loadScript`);
let elm = document.getElementById("number");
for(let i = 0; i < data.length; i++){
setTimeout(() => {
console.log(`Setting innerHTML as ${data[i]}`);
elm.innerHTML = data[i].toString();
},1000);
}
}
loadScript();
答案 0 :(得分:5)
循环将所有项的超时设置为1000毫秒,并且它们都在此时执行。一个简单的解决方案是将超时乘以i
:
setTimeout(() => {
console.log(`Setting innerHTML as ${data[i]}`);
elm.innerHTML = data[i].toString();
}, i * 1000);
const colorsRainbow = ["rgb(120,28,129)","rgb(64,67,153)","rgb(72,139,194)","rgb(107,178,140)","rgb(159,190,87)","rgb(210,179,63)","rgb(231,126,49)","rgb(217,33,32)"];
let num = 100
let data = [];
for (let i = 0; i < num; i++) {
data.push(Math.random() * 100);
}
console.log(data);
let elm = document.getElementById("number");
function loadScript(){
console.log(`Calling loadScript`);
for(let i = 0; i < data.length; i++){
setTimeout(() => {
console.log(`Setting innerHTML as ${data[i]}`);
elm.innerHTML = data[i].toString();
}, i * 1000);
}
}
loadScript();
<div id="map" style="width: 500px; height: 500px;">
<h1>Color Changer</h1>
<div id="number"></div>
</div>
但是,第一个解决方案一次为阵列的每个元素创建一个计时器。一个更好的解决方案是创建一个计时器,当它完成后再创建一个计时器:
function loadScript() {
setTimeout(() => {
console.log(`Setting innerHTML as ${data[i]}`);
elm.innerHTML = data[i].toString();
// increment i, and if i is less then the data length, call loadScript() again
++i < data.length && loadScript();
}, 1000);
}
const colorsRainbow = ["rgb(120,28,129)","rgb(64,67,153)","rgb(72,139,194)","rgb(107,178,140)","rgb(159,190,87)","rgb(210,179,63)","rgb(231,126,49)","rgb(217,33,32)"];
let num = 100
let data = [];
for (let i = 0; i < num; i++) {
data.push(Math.random() * 100);
}
console.log(data);
let elm = document.getElementById("number");
let i = 0;
function loadScript() {
setTimeout(() => {
console.log(`Setting innerHTML as ${data[i]}`);
elm.innerHTML = data[i].toString();
// increment i, and if i is less then the data length, call loadScript() again
++i < data.length && loadScript();
}, 1000);
}
loadScript();
<div id="map" style="width: 500px; height: 500px;">
<h1>Color Changer</h1>
<div id="number"></div>
</div>
答案 1 :(得分:0)
这是使用setInterval而不是setTimeout的版本。我发现setInterval比链接setTimeout调用更干净。
function loadScript() {
console.log(`Calling loadScript`);
let elm = document.getElementById("number");
let i = 0;
var intervalId = setInterval(() => {
console.log(`Setting innerHTML as ${data[i]}`);
elm.innerHTML = data[i].toString();
i++;
if (i === data.length) {
console.log('done');
clearInterval(intervalId);
}
}, 1000);
}