2 回答
TA贡献1891条经验 获得超3个赞
您可以在调用 a 时awaitfor a 。这样,函数就变成了每次完成后都会被调用:PromisesetIntervalasync
async function typeText(text, outputElement) {
var i = 0;
var paragText = "";
await new Promise(resolve => setInterval(function () {
paragText += text.charAt(i);
outputElement.innerText = paragText;
i++;
if (text.length == i)
resolve();
}, 70))
}
async function output(text, colour){
var outputElement = document.createElement("p");
outputElement.setAttribute("class", "output");
outputElement.setAttribute("style", "color: " + colour + ";");
var outputWrapper = document.getElementById("output");
outputWrapper.appendChild(outputElement);
await typeText(text, outputElement);
}
const init = async function() {
const outStrs = [
{text:"Test output 1",color:"red"},
{text:"Test output 2",color:"green"},
{text:"Test output 3",color:"blue"},
];
for (i =0; i < outStrs.length; i++){
await output(outStrs[i].text, outStrs[i].color);
}
}();
<div class = "output-wrapper" id = "output"></div>
TA贡献1886条经验 获得超2个赞
setTimeout与数组的解决方案
var delay = 90; // Writing speed
var arr = [ // Text and color Array
['Lorem ipsum dolor', 'red'],
['Consectetur adipisicing', 'green'],
['Earum voluptas', 'blue'],
];
function typeText(text, outputElement) {
var i = 0;
var paragText = "";
var interval = setInterval(function () {
paragText += text.charAt(i);
outputElement.innerText = paragText;
i++;
if (text.length == i)
clearInterval(interval);
}, delay)
}
function output(text, colour) {
var outputElement = document.createElement("p");
outputElement.setAttribute("class", "output");
outputElement.setAttribute("style", "color: " + colour + ";");
var outputWrapper = document.getElementById("output");
outputWrapper.appendChild(outputElement);
typeText(text, outputElement);
}
// Calculates setTimeout: Push the start time of each line in the array
var time = 0;
for (var i = 1; i < arr.length; i++) {
time = time + delay + arr[i-1][0].length * delay;
arr[i].push(time);
}
// Execute the writing process
var n = 0;
for (var i = 0; i < arr.length; i++) {
setTimeout(() => {
output(arr[n][0], arr[n][1]);
n++;
}, arr[i][2]);
}
<div class="output-wrapper" id="output">
</div>
添加回答
举报