-2

let fn_one = () => {
  setTimeout(function() {
    console.log("This is shashank");
  }, 5000)

}
let fn_two = (name, callback) => {
  setTimeout(function() {
    console.log("Hi!, " + name);
    callback();
  }, 1000)
}

fn_two("there", fn_one)

Here, fn_two is called and it executes after one second, however, it has a callback function which is set to fn_one(). So it should call the callback function immediately after it executes the fn_two function, right? Why is it taking 5 seconds after the fn_two is called? Why is it not working in background?

Can anyone explain to me why the function fn_one is taking 5 seconds even though I have called it as a callback function?

Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
Shashank KR
  • 83
  • 1
  • 9
  • Because `fn_one` schedules the `console.log()` after 5 second using `setTimeout(..., 5000)`? – Ivar Jun 19 '21 at 15:49
  • fn_one does get called by `callback()` straight away. If you put `console.log('fn_one called');` before the setTimeout in fn_one, you should see this. – Ben Stephens Jun 19 '21 at 15:53

1 Answers1

1

Inside the fn_one function there is a setTimeout of 5 seconds, regardless of where you call this function, inside it has a setTimeout function, it will only execute the code inside the setTimeout after the total time is reached.

To have a function with immediate return, you need to remove setTimeout:

let fn_one = () => {
  // setTimeout removed, it will run as soon as it is called.
  console.log("This is shashank");
}
let fn_two = (name, callback) => {
  setTimeout(function() {
    console.log("Hi!, " + name);
    callback();
  }, 1000)
}

fn_two("there", fn_one)
Yousaf
  • 27,861
  • 6
  • 44
  • 69