0

I seem to not be able to call the setInterval function like this:

this.timerHandler = setInterval(function(this.myTimerFunction){},1000)

It seems that if I make a global function and call that, the code works perfectly but it seems that calling a function locally using this, it won't work. I have tried calling this.myTimerFunction just before this line of code and it actually executes the code and works perfect, it's just that it seems it does not want to execute the function from a timer handler.

Any suggestions to try and fix this? this.myTimerFunction is a prototype function btw.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user312482
  • 13
  • 1
  • 3
  • Your syntax is invalid for starters. The call goes inside the function body, not in the parameter list. Then you need to invoke the function. Finally, you need to make sure `this` is what you intend for it to be,. – cookie monster Apr 10 '14 at 23:15
  • what do you expect "timerHandler" to be a property of ? – john Smith Apr 10 '14 at 23:16
  • 1
    [Learn how to debug JavaScript](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820) – Felix Kling Apr 10 '14 at 23:17
  • http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 under "the this variable" – HMR Apr 11 '14 at 05:11

3 Answers3

1

the syntax is wrong, you also have to take into account the context

var that=this; //save context

this.timerHandler = setInterval(function(){ //You can not use "this." like parameter
   that.myTimerFunction(params); 
},1000)

if you don't need send parameters in your function you can use

this.timerHandler = setInterval(this.myTimerFunction,1000);
Eduardo Ortiz
  • 407
  • 5
  • 12
  • Thanks. I found out that I did not bind the context as I do not want to call the function from the global scope. Thanks for telling me about the context. – user312482 Apr 11 '14 at 12:16
0

Try this:

this.timerHandler = setInterval(this.myTimerFunction, 1000);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I assume he doesn't want this to be window in myTimerFunction and therefore tries to pass a closure to setTimeout – HMR Apr 11 '14 at 05:08
  • Thanks. I found out that I did not bind the context as I do not want to call the function from the global scope. – user312482 Apr 11 '14 at 11:02
0

setInterval takes a function and an interval.

function(this.myTimerFunction){}

should just be:

this.myTimerFunction or this.myTimerFunction.bind(this)

You may not need the bind if the context doesn't matter.

SimpleJ
  • 13,812
  • 13
  • 53
  • 93
  • Thankyou so much!! I had no idea that when you call a function with setInterval, it run the function from the global scope. Again thanks, seems to work. :) – user312482 Apr 11 '14 at 11:00