I have few CPU intensive tasks to be performed on my web page which involve some calculations and drawing of texts. These tasks are supposed to be repeated at an interval (10-20 ms).
I decided to use Web Worker for this job, considering our target browsers are latest versions of major browsers which supports HTML5 & Web Worker.
The content of draw_worker.js
is something like in standard format:
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 15);
}
timedCount();
The content of function used by Worker is:
function startWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(w) == "undefined") {
w = new Worker("draw_worker.js");
}
w.onmessage = function(event) {
//Function to calculate & draw
calculateDrawData();
};
}
}
Things work fine on all major browsers on PC and Tablets without any issues. The calculateDrawData()
function is called at around 15-20 ms interval as I expect. But on few Tablets and phones things are not smooth. I investigated and found that calculateDrawData()
is not called at interval of around 15 ms and very frequently it takes up 70 ms or more before it is called.
I doubted that execution of calculateDrawData()
function might be taking long time. But after investigation found that calculateDrawData()
takes only 6-12 ms.
I'm just wondering what might be causing delay in interval at which onmessage
is being called. How to investigate it further?
I kept on working on this problem as I had no other choice after receiving no response at SO. The Developer tools
available in Chrome helped me in digging out root-cause. The "Performance" profiling was right tool to help in such cases. I selected Perfromance
tab in DevTools. The steps taken afterwards to analyse problem are:
CPU throttling
to "5 x slowdown".Main
section as those exhibits functions take longer time to execute. Summary
tab showed details of time distribution. Then selected Bottoms-Up
table for analysis of time taken by every function and sub-functions.The top level function was being called from a setInterval
call.
The function pointed out by Bottom-Up
section was taking about 70% of Total execution time.
The task was rather simple afterwards. The function in question had to be optimized.
The main point I want to raise here is that since un-optimized function was called from setInterval
it was able to interfere with Web Worker
and was even able to delay it.