PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 16, 2022

[FIXED] Why is timeout overridden?

 October 16, 2022     dom, javascript, settimeout     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing