tags:

views:

682

answers:

5

Hello all :)

I have a javascript that calls a function each 1 minute. That function sends a bot on the web looking for information to update on my database (quotes, to be exact).

So basically, sometime it's pretty fast and other times the servers dont answer fast... Let's say I have 100 seeks like this to make each 1 minute. They could take anywhere between 10 seconds to 1 minute+ to execute.

My question is : If the function is still fetching and/or waiting for data and I call it again (remember I call it each 1 minute), WILL IT CANCEL THE FIRST CALL to the function? If not, then will they simply stack and finish before starting the other one or will they run at the same time?

Thanks a bunch!

+1  A: 

It sounds like the answer is "don't count on it." If you're using something like setTimeout to kick off your function, you're at the mercy of your javascript engine as to whether it will actually run your code concurrently or if it'll just block the second execution until the first one finishes up.

http://www.howtocreate.co.uk/tutorials/javascript/timers

Also, whatever happens, it CERTAINLY shouldn't cancel the execution of the running function.

twon33
+2  A: 

Since you are on a single browser thread my guess is it will stack your calls

DroidIn.net
yes, +1 .
Luca Matteis
+1  A: 

Yes and no.

If your browser supports Web Workers then you can run multiple processes concurrently.

If it doesn't, then no you cannot run two processes at the same time. Even if you you setTimeout and give it a delay of 0, it will not. Doing that is actually like a yield. Your function will execute as soon as the current stack is executed.

geowa4
Ok so let's say I run it on the new Firefox 3.5, is this SURE they will thread?
Rock
I think that is starts to slow down after too many threads are started. But they do work concurrently.
geowa4
A: 

You may be interested in using Prototype's Function.PeriodicalExecuter to help you manage functions that take a long time to complete.

If including all of Prototype seems like overkill and you want to implement the functionality by hand, you could either have a boolean-flag that you set when an instance of the function is running; or a counter that is incremented at the head of the function, and decremented before it returns, giving you the total number of instances of that function.

If you are interested in using Prototype, another function that may help you out is Ajax.PeriodicalUpdater.

brownstone
+1  A: 

See How JavaScript Timers Work.

If you call your function using, setTimeout, e.g.

setTimeout(fn, 60000);

then the calls to fn will queue.

However, if your function makes an asynchronous HTTP request then potentially the responses will arrive out of order.

wrumsby