Search code examples
javascriptsetintervalfunction-calls

SetInterval calling method using .call(this) calls it only once


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.


Solution

  • 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.