0

I've been trying to run the following code but only the second function runs and the first one does not execute. Can anyone please let me know what's wrong.

function first() {
    setTimeout(function(){
            console.log(1);
          }, 500 );
};
 
function second(first) {
    console.log(2);
};

second();

What I'm expecting is that the program first displays 1 after 500ms and then 2.

3 Answers 3

1

What you expect :

function first() {
    setTimeout(function(){
        console.log(1);
        second();
    }, 500 );
};

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

first();

Your 'first' parameter in the second function does nothing. Instead you can do this too :

function first(callback) {
    setTimeout(function(){
        console.log(1);
        callback();
    }, 500 );
};

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

first(second);
Sign up to request clarification or add additional context in comments.

Comments

1

I think this is the effect you're trying to achieve. first accepts a callback function as a parameter. It then needs to be called somewhere inside of the first function.

function first(callback) {
  setTimeout(function() {
    console.log(1);
    callback(); // Calling the passed function
  }, 500);
};

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

first(second); // Passing the 'second' function as a callback

1 Comment

you most write console.log(1) before setTimeout
0

you just called second. you most call first for callback funtion for you expectation your code shoould be like this

function second() {
   setTimeout(function(){
       console.log(2);
   }, 500 );
};
     
function first() {
   console.log(1);
   second();
};

first();

2 Comments

Yes, but the second() is calling back first() but the output never shows 1. Not even after 2.
@saadi123 your second function didnt call first. you just have a parameter with name first in your second function

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.