0

Hello I am completely new to JavaScript and I am trying to do something , but I can't understand when I call this function:

this.start = function () {
    this.interval = setInterval(startIncrement.call(this) , 1000);
}

startIncrement only executes once. I am trying to do Counter class that generates two buttons(start and stop) and one textbox.So when I do:

var a = new Counter(); // generates object of Counter
a.init(); // generates the HTML (did that part)
a.start(); //start increasing the value of text box over period of time
a.stop(); // stops the counting (did that part)

And buttons start and stop simply have onclick event that call start and stop methods of Counter. I tried all answers of this question setInterval only runs once on object method but it didn't work and now I am stuck.

Community
  • 1
  • 1
kuskmen
  • 3,648
  • 4
  • 27
  • 54
  • 1
    The first answer to that question is the answer to your question: setInterval expects a function to be passed to it, and you're passing the result of calling your "startIncrement" function. Perhaps you meant `.bind()` instead of `.call()`. – Pointy Oct 25 '15 at 19:15
  • Yes, now that you say it like that it makes total sense , but sadly I don't know when to use call , bind or apply I've read about them , but I seem to be misusing them.. could you explain to me how they works if you have the time? Thanks in advance. P.S I already asked spender to do so , but if you want you can do it too :) – kuskmen Oct 25 '15 at 19:22
  • Well @spender explained `.bind()` which is the only one of the three that gives you back a function to use later. Both `.call()` and `.apply()` are ways to invoke a function immediately; they're different in detail but they do basically the same thing. – Pointy Oct 25 '15 at 19:27

1 Answers1

3

Using the .call method of a function invokes it immediately, with the (first) parameter becoming this to the contents of the function.

By using

setInterval(startIncrement.call(this) , 1000);

you're calling the startIncrement method immediately and using whatever it returns as a parameter to setInterval. Unless it returns a function, that's not what you want.

Did you mean:

setInterval(startIncrement.bind(this) , 1000);

?

.bind will hand you back a function that, when you call it, is assured to have the (first) parameter as the this object. It does not invoke the function. It creates a new function that wraps around the original function, doing a small amount of work to change the this object when it calls the original function that it wraps.

spender
  • 117,338
  • 33
  • 229
  • 351
  • YES! I must have misunderstood the functions .. in fact could you explain me more about apply,call and bind because I've been reading for them for one hour and I seem to be using them unproperly.. if you have time of course. – kuskmen Oct 25 '15 at 19:20