Consider an application which periodically executes a background task via setTimeout / setInterval. What’s the ideal amount of work one function call should do?
Example:
myTask = function() {
for (var i=0; i<chunkSize; i++) { ...work... }
}
setInterval(myTask, period);
If you increase chunkSize (and do more iterations per call), of course it will run longer. That means, the period will also have to increase and you can call the function less often. But I found that nevertheless, the bigger the chunks, the more work gets done. This is probably due to overhead of setTimeout / setInterval
The trade-off is: bigger chunk sizes make the application less reactive. This does not only concern user interaction, but also other intervals. Because as long as the function is running its iterations, no other interval can get triggered. Thus, big chunk sizes make other intervals less accurate, or (in the worst case) completely disable them in some browsers so they don’t get called anymore.
If you want to
- maximize the amount of work getting done
- minimize bad influence on other intervals and keep them accurate
what is the best way to achieve that? How do you determine a good chunkSize? Or should I monitor execution times in the loop and abort after a certain time? Or something else?
(btw, this is about plain old JavaScript, not HTML5 WebWorkers)
If you can, you should use
setTimeoutinstead ofsetInterval.setIntervalwill call the function afterperiodwhether the function from the previous interval is complete or not. WithsetTimeout, you can make sure the function is complete before it called again.