简体   繁体   中英

Javascript binding using call with setInterval

How can I use "call" with "setInterval" to get an object literal to invoke one of its own methods?

Here's an example. This works, and I understand why it works. The timer object calls its own tick method once each second

var timer =
{ 
  start: function()
  {
    var self = this;
    setInterval(function(){self.tick();}, 1000);

  },

  tick: function()
  {
    console.log("tick!");
  }
};

timer.start();

I tried to simplify this code by using "call". This next example is the best that I came up with. But it doesn't work: the tick method is called only once, and then I get a type error.

var timer =
{ 
  start: function()
  {
    setTimeout.call(this, this.tick(), 1000);
  },

  tick: function()
  {
    console.log("tick!");
  }
};

timer.start();

I think I don't really understand how call works. Can anyone explain what I'm doing wrong?

You are .calling .setInterval not your callback function which the browser calls:

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

Should work. See .bind

This is what I ended up with:

  var timer = {
    time: 0,
    start: function() {
      var timerTick = this.tick.bind(this);
      window.setInterval(function() {
        timerTick();
      }, 1000);
    },
    tick: function() {
      this.time += 1;
      console.log(this.time);
    }
  };

  timer.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM