0

I have a class with a method which is instanced as a object. When element is clicked this should call object method. Both calls work. However, I expected 2nd call to have delay of 75000. However, there is no delay at all. It makes second call without any delay. I am using ECMAScript6 here.

class Test {
  foo(x){
    switch (x) {
      case 1:
        alert('test1')
      break;
      case 2:
        alert('test2');
      break;
    }
  }
}

var test = new Test();
$('#test-trigger').click(function() {
  test.foo(1);
  setTimeout(test.foo(2),75000)
});
Kunok
  • 8,089
  • 8
  • 48
  • 89
  • Thats because you're calling `test.foo(2)` straight away. – putvande Jan 25 '16 at 11:42
  • _“It makes second call without any delay”_ – _you_ are calling the method directly, because that’s what `()` at the end _does_. You need to pass a function _reference_ to setTimeout. – CBroe Jan 25 '16 at 11:42

1 Answers1

3

You are calling the function in the setTimeout instead of passing function as parameter. You can create a new function (from the old one), bind it and prepend parameter to it with Function.prototype.bind():

setTimeout(test.foo.bind(test, 2), 75000);
madox2
  • 49,493
  • 17
  • 99
  • 99