Module, setInterval and this..

Posted on
  • Hi

    I've tried to write a clock module, but it needs to do an internal setInterval to call an internal function. I tried to setInterval(this.tick,1000) but it fails.

    I think I found some example code - this defines the function to be called by setInterval in the exported init function - which I think means it will be cloned every time the class is used - which wastes memory a bit.

    Is there any way to have a module function that is called by setInterval...?

    Thanks

    Martin

  • Hi Martin,

    Yes - it should be possible. The issue is probably with what happens to the this variable when called from setInterval. It's a standard JS thing...

    You could try something like this:

    Clock.prototype.start = function() {
      var me = this;
      setInterval(function() { me.tick(); },1000);
    }
    

    This will define a function for each setInterval, but it'll be relatively small.

    I'm not sure quite what you're planning, but I wonder how many clock modules a user might have? If it's 1 or 2 it might not matter if the function is duplicated.

  • Thanks Gordon.... I wasn't sure this was standard JS. I understand it a bit
    better now... This business of JS copying out functions seems a bit memory heavy...

    The use case for this is just as a general purpose clock. I guess in a typical project there would be just one instance, so it's fine.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Module, setInterval and this..

Posted by Avatar for mgg1010 @mgg1010

Actions