1

I know 2 will be console.logged first and then 1. Is there any way, maybe with callbacks, I can show 1 first and then 2?

function first(){
  // Simulate a code delay
  setTimeout( function(){
    console.log(1);
  }, 500 );
}
function second(){
  console.log(2);
}
first();
second();
4
  • Call second() in timeout Commented Dec 11, 2018 at 8:02
  • Don't call first or second; just do console.log(1); console.log(2);. Commented Dec 11, 2018 at 8:03
  • don't use timeout call in first function Commented Dec 11, 2018 at 8:04
  • Promise is better than callback. Commented Dec 11, 2018 at 8:27

4 Answers 4

1

Put second()'s call in the setTimeout:

function first(){
  // Simulate a code delay
  setTimeout( function(){
    console.log(1);
    second();
  }, 500 );
}
function second(){
  console.log(2);
}
first();

You could also bypass first, second and setTimeout completely:

console.log(1);
console.log(2);
Sign up to request clarification or add additional context in comments.

Comments

1

function second(){
  console.log(2);
}

function first(cb){
  // Simulate a code delay
  return setTimeout( function(){
    console.log(1);
     cb();
  }, 500 );
   
}

first(second);

Comments

1

Solve it by promise a clan and elegant way:

function second() {
	console.log("test2", 2);
}

function first() {
	var promise = new Promise(function (resolve, reject) {
		setTimeout(function () {
			console.log("test1", 1);
			resolve();
		}, 500);
	});
	return promise;
}

first().then(function () {
	second();
});

Comments

0

don't use timeout call in first function. or you can use promises

for better understanding of event loop callback execution order read this article link. this article explains execution order , which get priority among promise , timeout etc

Hope it will help

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.