Web workers - How do they work?

后端 未结 2 1729
失恋的感觉
失恋的感觉 2020-12-20 18:40

I\'m trying to understand this example:

HTML (main code):

     
     Test threads fibonacci  
     

        
2条回答
  •  心在旅途
    2020-12-20 19:13

    Check out HTML5 Rocks: The Basics of Web Workers for general tutorial.

    • Workers will start as soon as you call the postMessage method of the worker.
    • the function bound to worker's onmessage in the main code will work when the worker calls postMessage.
    • global variables are not shared between main and worker threads. The only way to pass data is through messaging via postMessage.
    • as you suspected, the onmessage on both worker and main code has the same meaning. It is an event handler for when the thread receives a message event. You can even use addEventListener instead, catching message event:

    Main Code:

    function showResult(event) {  
       document.getElementById("result").textContent = event.data;  
       dump("Got: " + event.data + "\n");  
    }
    var worker = new Worker("fibonacci.js");
    worker.addEventListener('message', showResult, false);
    

    Worker code:

    addEventListener('message', resultReceiver, false);
    

    The fibonacci example you took is a recursive worker example. If not using workers, it would be something like this:

    function fibonacci(n) {
        if (n == 0 || n == 1) return n;
        return fibonacci(n-1) + fibonacci(n-2);
    }
    
    var result = fibonacci(5);
    dump("Got: " + result + "\n");
    

    (oh no, I'm not going to do a stackless for you. You write it yourself!)

提交回复
热议问题