-2

I have read this post about executing a function every n seconds, but I am working with classes and want to execute the method every n seconds.

I have 2 objects, and each one will have a method that will execute every n seconds.

class MyClass {
  constructor() {
    //stuff
  }
  myMethod() {
    //other stuff to execute every n seconds
  }
}

var obj1 = new MyClass()
, obj2 = new MyClass();

How would I go about doing this?

EDIT: Sorry for the confusion, but i wanted to be able to use the this keyword in the interval

Ank i zle
  • 2,089
  • 3
  • 14
  • 36

1 Answers1

0

You can simply use setInterval to call a function every n milliseconds:

class MyClass {
  doSomething() {
    console.log('doSomething() called..')
  }
}

var o = new MyClass();

setInterval(o.doSomething, 1000);
Tom O.
  • 5,730
  • 2
  • 21
  • 35