Issue
const screenDiv = document.getElementById('screen');
function outputKorv() {
const paragraph = document.createElement('p');
screenDiv.appendChild(paragraph);
const korv = new Array('k', 'o', 'r', 'v');
let index = 0;
while (index < korv.length) {
const letter = document.createTextNode(korv[index]);
setTimeout(console.log(letter), 1000);
index++;
}
}
outputKorv();
When I run the script the letters are written to the console immidiately, and not as I expected with a 1 second gap between them. I've also tried to put the increment in the timeout, but I can't get that to work either. I've tried: setTimeout(index++, 1000)
, setTimeout('index++', 1000)
, and setTimeout(() => index++, 1000)
, but neither works. I've also tried a for loop, and do ... while, but I'm getting the same result with those too. The idea is to output the word 'korv' to an HTML-page one letter at a time. Can someone explain what I'm doing wrong?
Solution
My recommendation is: Make the function async
, define a delay function as const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
and then simply call await delay(1000)
at the point where you want to wait. This will greatly simplify the logic.
Here is the updated code. I took the liberty to also replace the verbose while
loop with a for
loop and get rid of the deprecated new Array
syntax.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const screenDiv = document.getElementById('screen');
async function outputKorv() {
const paragraph = document.createElement('p');
screenDiv.appendChild(paragraph);
const korv = ['k', 'o', 'r', 'v'];
for (let index = 0; index < korv.length; index++) {
const letter = document.createTextNode(korv[index]);
console.log(letter)
await delay(1000);
}
}
outputKorv();
Answered By - CherryDT Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.