1

I'd like to wait 1 minute and then execute a function f(). I have found out that in Javascript there isn't a sleep() function but I can use setInterval() or setTimeout() functions.

The window.setInterval() function works, but this is not what I want. I want to execute f() only once. I tried to use the setTimeout() function as follows.

var MyNamespace {
  ...
  f: function() {
  },
  ...
  click: function() {
    ...
    setTimeout("this.f()", 60000); // f() is never executed
    // setTimeout(this.f(), 60000); f() is executed immediately without timeout
    // window.setTimeout(...) doesn't help
  },
  ...
}

What could be wrong here?

The code is part of a Firefox extension.

intika
  • 8,448
  • 5
  • 36
  • 55
xralf
  • 3,312
  • 45
  • 129
  • 200

4 Answers4

4

There's your problem: "this.f()". Replace it with:

setTimeout(this.f.bind(this), 60000);

and it should work. Passing a string to setInterval() is never a good solution, just like using eval().

See also

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
3

Try

setTimeout( this.f.bind(this), 60000 );

Never pass a string to setTimeout as it will be evaluated in global context.

Esailija
  • 138,174
  • 23
  • 272
  • 326
1

Also check out the nsiTimer if you're running the timer in chrome: https://developer.mozilla.org/en/nsITimer

Yansky
  • 4,580
  • 8
  • 29
  • 24
0

As the code is intended for a firefox extensions you should use

setTimeout(function() { alert('timeout') },2000);

setTimeout(alert('timeout'),2000); // will be executed directly, not suitable 
intika
  • 8,448
  • 5
  • 36
  • 55