问题
I have a complex javascript function which could take 1 second, or many minutes sending an answer. So I created a Worker which is working, I'm calling this function from my UIWebView in Swift (stringByEvaluatingJavaScriptFromString). I'm waiting only 5 seconds (timeout created in the same Javascript), after that I terminate the worker (job.terminate()), and I start a different one with other parameters (simplier), which takes only 1 second in show the answer. The thing is, the first worker seems to be running in background even after the terminate signal. AS you can see in the image, the WebCore: Worker has a lot of CPU usage. How can I relly terminate the worker?
job = new Worker("main.js");
var t = setTimeout(function(){
stop();
logNode.innerText = 'NULL';
},5000);
function stop() {
job.terminate();
job = undefined;
}
(main.js):
importScripts('dist/algorithm.js');
var lp;
self.addEventListener('message', function(e) {
...
...
回答1:
the easiest way to terminate the worker (and be sure of it) would be to inject a boolean expression to cause the code to "exception out" of its main loop (or even return gracefully if there is only 1 or 2 bottlenecks in the code.). and you can perform any required cleanup in a catch block prior to letting it exit naturally.
I personally hate ending threads with functions such as terminate or kill because it can leave things in a undefined state
The call to terminate may get ignored or enqueued for later simply because the worker is using all the resources it can leaving no time for message processing.
来源:https://stackoverflow.com/questions/28402685/ios-javascript-workers-high-cpu-after-terminate