views:

559

answers:

3

I'm messing around with building an application for the Palm Pre.

I have a simple question: How can I set up a timer for some code to get run after a certain amount of time has passed?

I tried using the regular old javascript setTimeout, but it doesn't seem to work.

Here is what I've tried:

setTimeout(this.someFunction, 3000);
setTimeout('this.someFunction()', 3000);

Neither one seems to work. How can I accomplish this?

+3  A: 

Turns out that the prototype javascript framework is used by Mojo.

I was able to solve this issue by using:

this.someFunction.delay(seconds, [functionArgs,]);

One thing that tripped me up was that the delay method changed the value of this, so the delayed function must not expect that this will be the same as if you had simply invoked it directly.

TM
How do you get around the "this" issue you described. What if I had a model called txtmodel with a property called value. Outside of the delay function, I would just call this.txtmodel.value = 'foo'
Cody C
Okay, this was just a "duh" moment for me. I simply am passing in a reference to this to my delay function and it works. Thanks for the tip!
Cody C
@cody Another (possibly better) solution is to use prototypes "bind" method to make sure that "this" is always what you expect it to be when that method is called.
TM
A: 

Do you mind sharing some more details of how you got it to work. I am having the same issue but even trying the

this.someFunction.delay(seconds, [functionArgs,]);

In my case:

this.testTimeout.delay(1000);

Won't do anything either.

I even started on a clean slate with nothing else in it just the setTimeout/delay lines and well I can't get it to work.

C.M.

The delay function takes SECONDS, not MILLISECONDS the way setInterval does. That code is waiting 1000 seconds before executing (almost 17 minutes!).
TM
A: 

@TM: Thanks for pointing out Prototype's bind() method. I was struggling with the setTimeout() problem yesterday and ended up using Prototype's delay() method like you pointed out, and then this morning I saw in Mitch Allen's "Palm webOS" book that he was calling setTimeout() on the this.controller.window object, like so:
this.controller.window.setTimeout(this.someFunction.bind(this), someNumberOfMilliseconds);

I don't think I would have noticed the use of this.controller.window if I had not been looking for exactly that solution, and now I'm noticing several places in the book where this.someFunction.bind(this) is used, although he never explains what that does. Now I know!

Daren