TechnoCorner
TechnoCorner

Reputation: 5165

Javascript callback not getting invoked

I'm trying to run this snippet and it doesn't seem to be executing callback. I'm trying to understand what's going on.

  function exampleSimpleTask(done) {
    console.log("task", "Before "+new Date().getTime());
    setTimeout(() => done, 2000);
  }

 function demo() {
   alert("Demo Executed");
 }

 exampleSimpleTask(demo); // it doesn't do anything.
 //  exampleSimpleTask.call(null, demo);
 // exampleSimpleTask.call(null, demo.bind(this)); 

I'm not sure why the callback is executed, I'm suspecting its something to do with arrow functions. What happens if => is replaced by function()?

Upvotes: 0

Views: 35

Answers (4)

Barmar
Barmar

Reputation: 782508

There's no need for the arrow function in setTimeout. The first argument to setTimeout() is the function you want to execute when the time is reached, and done contains a reference to the function, so just pass it directly.

  function exampleSimpleTask(done) {
    console.log("task", "Before "+new Date().getTime());
    setTimeout(done, 2000);
  }

 function demo() {
   alert("Demo Executed");
 }

 exampleSimpleTask(demo); // it doesn't do anything.
 //  exampleSimpleTask.call(null, demo);
 // exampleSimpleTask.call(null, demo.bind(this)); 

Upvotes: 1

zfrisch
zfrisch

Reputation: 8670

inside your function exampleSimpleTask you never call the function done

function exampleSimpleTask(done) {
  console.log("task", "Before "+new Date().getTime());
  setTimeout(() => done(), 2000);
}

function exampleSimpleTask(done) {
    console.log("task", "Before "+new Date().getTime());
    setTimeout(() => done(), 2000);
  }

 function demo() {
   alert("Demo Executed");
 }

 exampleSimpleTask(demo); 

Upvotes: 0

Shidersz
Shidersz

Reputation: 17190

You forgot to add the parenthesis for call the demo method:

function exampleSimpleTask(done)
{
    console.log("task", "Before "+new Date().getTime());
    setTimeout(() => done(), 2000);
}

function demo()
{
    alert("Demo Executed");
}

exampleSimpleTask(demo); // it doesn't do anything.

As an alternative, you can simple put the name of the method on the setTimeout() function, like this:

function exampleSimpleTask(done)
{
    console.log("task", "Before " + new Date().getTime());
    setTimeout(done, 2000);
}

function demo()
{
    alert("Demo Executed");
}

exampleSimpleTask(demo); // it doesn't do anything.

Upvotes: 1

Kevin Furmanski
Kevin Furmanski

Reputation: 110

You have forgotten to call the done() function inside the lambda expression. The code below should work:

  function exampleSimpleTask(done) {
    console.log("task", "Before "+new Date().getTime());
    setTimeout(() => done(), 2000);
  }

 function demo() {
   alert("Demo Executed");
 }

 exampleSimpleTask(demo); // it doesn't do anything.
 //  exampleSimpleTask.call(null, demo);
 // exampleSimpleTask.call(null, demo.bind(this)); 

Upvotes: 1

Related Questions