jai__
jai__

Reputation: 23

How does one have the console.log or prompt occur after an interval

I am using console.log() in a simple program

console.log("Welcome");
var name = prompt("What is your name?");
console.log("Hello" + name);

But the prompt occurs before the Welcome message. Is there a way to have these messages in sequence or is there an alternative.

I want the Welcome message to occur before the prompt, but it that does not happen and the prompt comes before ruining the flow of the program.

Upvotes: 2

Views: 643

Answers (3)

Nick Parsons
Nick Parsons

Reputation: 50974

One possible way to achieve what you're after is to use use a Promise with async/await which will resolve after setTimeout call is complete. This way you can make your own "sleep" like function and thus "pause" the program before prompting the user:

const sleep = t => new Promise(res => setTimeout(res,t));

(async _ => {
  console.log("Welcome");
  await sleep(1); // sleep for 1 milisecond
  var name = prompt("What is your name?");
  console.log("Hello " + name);
})();

Alternatively, you could use alert() for your outputs instead of using console.log():

alert("Welcome");
var name = prompt("What is your name?");
alert("Hello " + name);

Upvotes: 1

Randy Casburn
Randy Casburn

Reputation: 14185

Here is the simplest solution...

const p = new Promise((resolve) => {
  console.log("Welcome");
  resolve();
});

p.then(() => {
  var name = prompt("What is your name?");
  console.log("Hello" + name);
});

Recommend against the use of timeouts as they are unreliable for this purpose. This code simply says "do this", then "do that" in sequence.

Upvotes: 0

Scott Sauyet
Scott Sauyet

Reputation: 50807

Here is a simple version:

console.log("Welcome");
setTimeout(() => {
  var name = prompt("What is your name?");
  console.log("Hello " + name);
}, 0)

You simply have to move the prompt to the next tick. setTimeout will do it.

Upvotes: 0

Related Questions