1. 程式人生 > >web worker 簡介

web worker 簡介

ons 就是 ner nac htm now() 需要 OS tar

web worker 簡介

通常,瀏覽器執行某段程序的時候會阻塞直到運行結束後在恢復到正常狀態,而HTML5的Web Worker就是為了解決這個問題。通過worker線程完成密集計算,避免程序的阻塞和頁面的卡頓(fps過低)

示例

用fibonacci數列來模擬測試

worker-test.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>測試 web worker</title>
</head>

<body>
    <script>
        function fibonacci(n) {
            return n < 2 ? n : arguments.callee(n - 1) + arguments.callee(n - 2);
        }


        function testNoWorker() {
            let start = Date.now();
            fibonacci(38);
            let end = Date.now();
            console.log(end - start); // wait a long time..
        }

        function testUseWorker() {
            let start = Date.now();
            let worker = new Worker(‘worker.js‘);
            worker.postMessage(38);
            worker.addEventListener(‘message‘, function (event) {
                let end = Date.now();
                console.log(‘worker result: ‘, end -start);
            });
            console.log(‘can do other jobs, when worker is computing‘);
        }

        testNoWorker();
        testUseWorker();
    </script>
</body>

</html>

worker.js

function fibonacci(n) {
    return n < 2 ? n : arguments.callee(n-1) + arguments.callee(n-2);
}

self.addEventListener(‘message‘, function (event) {
    let result = fibonacci(event.data);
    self.postMessage(result);
});

假設主頁面需要多次執行耗時的操作(如: fibonacci), 可如下用worker來異步執行.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>測試 實例化多個 web worker</title>
</head>

<body>
    <script>
        function fibonacci(n) {
            let start = Date.now();
            let worker = new Worker(‘worker.js‘);

            worker.addEventListener(‘message‘, function (event) {
                let end = Date.now();
                console.log(‘worker result: ‘, end - start);
            });
            worker.postMessage(n);
        }

        /* 同時跑多個worker, 會降低每個worker線程的性能;但總比阻塞頁面要好 */
        fibonacci(38);
        console.log(‘after one‘);
        
        fibonacci(38);
        console.log(‘after two‘);
        
        fibonacci(38);
        console.log(‘after three‘);

        console.log(‘can handle other jobs..‘);


    </script>
</body>

</html>

web worker 簡介