skip to Main Content

We have 5 statements in a line and If we have a set timeout in the 3 statement it will executed after all the remaining statement got executed. I’m looking to execute the each statement line by line even If we have a set timeout in-between the code.

Example:
We have some statements

console.log("A");
setTimeout(console.log("B"), 1000);
console.log("C");

The expected output is A C B but I want to print is a A B C.
Any thoughts on this?

2

Answers


  1. I assumed your setTimout was incorrect since it WILL execute the console.log immediately.

    To do what you want, you need to replace console and setTimeout

    const myMessages = [];
    const myConsole = window.console;
    window.console = { log: (str) => myMessages.push(`mine: ${str}`) }
    const myTimeout = window.setTimeout;
    window.setTimeout = func => {
      myMessages.push(func)
    };
    console.log("A");
    setTimeout(() => console.log("B"), 1000);
    console.log("C");
    window.console = myConsole; // reset
    myMessages.forEach(msg => {
      if (typeof msg === "string") console.log(msg)
      else msg()
    })  
    Login or Signup to reply.
  2. you need to chain the timeouts, something like this (treat this as a proof of concept, but it is tested)

    <script>
    var linesToPrint = ['A', 'B', 'C'];
    function WriteNextLine(lineCount)
    {   if (linesToPrint[lineCount] != undefined)
        {   console.log(linesToPrint[lineCount]);
            setTimeout(function(){WriteNextLine(++lineCount);}, 1000);
        }
    }
    WriteNextLine(0);
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search