Is it possible to 'thread' Javascript and keep access to the UI?

后端 未结 3 1081
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 18:02

I would like to thread some Javascript code while both the main process and thread are free to update the browser UI.

For example:

function StartStuf         


        
3条回答
  •  無奈伤痛
    2020-12-06 18:21

    As of 2009 (FF 3.5/Gecko 1.9.1) a new Web API was added that is called Web Workers. It works also on Chrome 4+, Opera 10.6+ and IE10+.

    The worker is basically a background thread that runs in a separate process.

    The communication between the master process (eg. your UI's main thread) and the slave process (the background thread, the worker) is established with the aid of a generic PostMessage/onmessage function where you can exchange whatever data you like between the two parties.

    It is worth mentioning that every single worker is assigned to a different core. For instance by creating 4 different workers (that do a long-running computation) on a quad-processor you are going to see all the 4 CPU-cores like 100% while the main-script is still idling and thus responding to your UI events (look at this example).

    A basic example:

    main-script.js

    if ("function" !== typeof window.Worker) {
      throw "Your browser doesn't support Web Workers";
    }
    var thread = new Worker("background-thread.js");
    thread.onmessage = function(e) {
      console.log("[A] : I received a " + e.data + " :-P");
    };
    thread.onerror = function(e) {
      console.log(e);
    };
    
    console.log("[A] : I'm sending a PING :-)");
    thread.postMessage("PING");
    

    background-thread.js

    onmessage = function(e) {
      console.log("[B] : I receveid a " + e.data + " :-)");
      console.log("[B] : I will respond with a PONG ;-)");
      postMessage("PONG");
    };
    

    The above example should produce the following output at your browser's console:

    [A] : I'm sending a PING :-)

    [B] : I receveid a PING :-)

    [B] : I will respond with a PONG ;-)

    [A] : I received a PONG :-P

    So happy PING-ing to your background script!

提交回复
热议问题