JavaScript. Interval for its own properties



  • I don't understand how to use intervals to address the properties of the facility. Please help. There's nothing on the Internet.

    There's a code like this:

    example = new Example();
    function Example() {
        this.TIME = 500;
        this.counter = 0;
        this.interval = null;
        this.step = function() {
            console.log(++this.counter);
        }
        this.start = function() {
            this.stop();
            this.interval = setInterval(this.step, this.TIME);
        }
        this.stop = function() {
            clearInterval(this.interval);
        }
    }
    

    Function example.step(); It works right. On call. example.start(); It is reported that the variable counter is not a number.



  • On call. setInterval/setTimeout losing context, variable this refers to another object with no properties counter

    The most modern and simple way to preserve the context in the bell is to use bind(): setInterval(this.step.bind(this), this.TIME);♪ But this is the way. https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Browser_compatibility IE8 and other old browsers.

    The safest way is to keep this reference to the variable and to transfer an anonymous function to set Interval:

    var self = this;
    this.interval = setInterval(function () {self.step()}, this.TIME);
    

    If you usere ES2015, you can use the extra variable:

    this.interval = setInterval(() => this.step(), this.TIME);
    

    https://jsfiddle.net/alexey_m_ukolov/cas2k1cu/1/




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2