-1

I want to stop the execution of my code by 2 seconds so that all the on going animation can get finished. I am trying to call a function using setTimeout in Node.js

what I am doing in my code :

this.userActivity = function(a,b,side){
     //some code of mine
     setTimeout(this.doTheMagicIfPossible(this.scoringPossible),2000);
}

this. doTheMagicIfPossible = function(passedValue){
     console.log("printing it out after 2 seconds"+passedValue);
}

But, execution is not getting stopped for 2 seconds.

If I do like this:

setTimeout(this.doTheMagicIfPossible,2000,this.scoringPossible);

Execution is getting stopped by 2 seconds but function is not getting this.scoringPossible, it's undefined in this case.

Renaissance
  • 566
  • 6
  • 26

1 Answers1

1

Sort of. You aren't seeing execution stopping for 2 seconds, because you are actually calling doTheMagicIfPossible from inside your setTimeout call.

If you want to pass parameters to the callback passed to setTimeout, you need to pass in a function taking no arguments that provides the correct arguments to your callback. Javascript provides the function bind in Function's prototype to do just this, for example:

setTimeout(this.doTheMagicIfPossible.bind(this, this.scoringPossible),2000);

Here, bind creates a new function, taking no arguments, which when called will call doTheMagicIfPossible with this set to the same this, and this.scoringPossible as the first argument.

slugonamission
  • 9,328
  • 29
  • 39
  • With less magic: `var me = this; setTimeout( function(){ me.doTheMagicIfPossible(me.scoringPossible) }, 2000 );` where `me` is used to refer to `this` later on, where it may have changed. – Phrogz Jul 22 '16 at 20:55