Simo03
Simo03

Reputation: 273

setTimeout wait to execute what's after

I want to know how to make setTimeout wait before executing what comes after.

setTimeout( function() { console.log("First"); }, 5000 );
console.log("Second");

In the console I want to see: First Second

"First" after 5 seconds and then "Second" just after "First" But what's really happening is that I have "Second" and after 5 seconds "First"

How can this be fixed ?

Upvotes: 0

Views: 1718

Answers (5)

Stanislav Kvitash
Stanislav Kvitash

Reputation: 4622

If IE is not priority and you allowed to use Promise, then you can use a simple wait function to work as setTimeout and return Promisewhich allows for method chaining:

function wait(t) {
   return new Promise(function(resolve) { 
       window.setTimeout(resolve, t)
   });
}

wait(5000)
.then(function(){ console.log("First"); })
.then(function(){ console.log("Second"); });

Upvotes: 4

Cedric Ipkiss
Cedric Ipkiss

Reputation: 6337

I want to know how to make setTimeout wait before executing what comes after.

I think the JavaScript function for "wait" is setTimeout. Meaning you can achieve this by nesting one setTimeout function inside another.

setTimeout(function() {
  setTimeout(function() {
    console.log('Second');
  }, 100);
  console.log('First');
}, 5000);

Upvotes: 0

SteveKitakis
SteveKitakis

Reputation: 172

If you are executing more than just a console log after, you can write a new function to run after the setTimeout. Anything in the "second" function will occur after logging "First".

var second = function () {
    console.log("Second");
}

setTimeout( function() { 
    console.log("First");
    second();
}, 5000 );

Upvotes: 0

Freeman Lambda
Freeman Lambda

Reputation: 3655

Javascript does not guarantee linear order of execution in your code. You can't expect your code to execute line by line when introducing timeouts or asynchronous tasks.

You could print both lines within the resolving function:

setTimeout(function() {
  console.log("First");
  console.log("Second");
}, 5000);

Upvotes: 0

Igor
Igor

Reputation: 15893

setTimeout( function() { console.log("First"); }, 1000 );
setTimeout( function() { console.log("Second"); }, 1000 );

Upvotes: 0

Related Questions