开发者

Sleep inside JavaScript web worker without sacrificing CPU resources

Overview: Our company has a need for web application that has access to local resources (RS232 / serial devices). After so开发者_如何学Pythonme research and POC we've discarded options like ActiveX, Java Applets and decided to create local application (written in C# which will be later transofmed to a service and distributed to the customers) that reads serial data and serves them over HTTP protocol (simple TCP server answering necessary headers + plain serial data). Then the web application does AJAX to 'http://localhost:8080' reading those data.

All this is done in a web worker in a while loop posting message to the main thread filling it in a form's input element. By serving static content I am able to get decent performance. On an older Intel Dual Core (not Core 2 Duo) 1,6GHz CPU in Chrome 13 on Windows there are 300-350 iterations per second and 5 - 9% CPU taken by the web worker thread.

Q: What I want to achieve now is to throttle polling interval in the web worker by inserting some sort of sleep() function after each ajax request, e.g. experiment with 100ms in the beginning.

What would be the best solution without sacrificing CPU resources in the thread?

Note: I could insert some delay in the TCP server code as the last resort.

EDIT:

I need to sleep inside worker. Example (oversimplified for clarity):

AJAX = new XMLHttpRequest();
while (true) {
  AJAX.open("GET", "http://127.0.0.1:8080", false);
  AJAX.send(null);
  var ean = AJAX.responseText;
  if (ean != '') { postMessage(ean); }
  /* NEED TO SLEEP HERE WHETHER THE RESPONSE WAS SENT OR NOT */
}


I think the best solution would be the WebSocket API. So, you can attach a event listener in your web application and fire it from C# every time you need some action.


Unfortunately there is no sleep, or wait, function in javascript - but you can emulate one with the use timeouts and callbacks. ("Jumping" to the rest of your code through a callback function - and placing the call in a setTimeout method).

EDIT:

You can do something like this,

AJAX = new XMLHttpRequest();
var myInterval = setInterval( function(){
    AJAX.open("GET", "http://127.0.0.1:8080", false);
    AJAX.send(null);
    var ean = AJAX.responseText;
    if (ean != '') { postMessage(ean); }
},120);

Now if you don't awnt to wait for the first call, place it outside of the interval (so it is ran instantly) and then call the interval again as it is written above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜