简体   繁体   中英

Javascript : can i automatically call a function many times even if it has not finished being executed?

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!

由于您使用的是单个浏览器线程,所以我猜它会堆积您的调用

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.

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.

See How JavaScript Timers Work .

If you call your function using, setTimeout , eg

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM