HTML5 Web Workers use

1. What is a Web Worker?

web worker is a JavaScript running in the background and does not affect the performance of the page. (Similar to c # background thread?)

2. How to use

Counter example:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8" />
</head>
<body>
    <p>计数<output id="result"></output></p>
    <input type="button" value="开始" onclick="start()" />
    <input type="button" value="结束" onclick="stop()"/>
</body>
</html>
<script type="text/javascript">
    var w;
    function start()
    {
        if (typeof (Worker)!="undefined") //判断浏览器是否支持Worker功能
        {
            if (typeof (w) == "undefined")
            {
                w = new Worker("/Scripts/Worker.js"); // JS loading a custom 
            } 
            w.onmessage = function ( Event ) // Returns the message 
            { 
                document.getElementById ( " Result " ) = .innerHTML Event .data; // data message 
            } 
        } the else 
        { 
            document.getElementById ( " Result " ) .innerHTML = " does not support the worker " ; 
        } 
    } 

    function STOP () 
    { 
        w.terminate (); this method is used to end // worker 
        W = undefined;

    }
</script>
Worker.js (do an automatic thread addend)
var i = 0;

function timedCount() {
    i = i + 1;
    postMessage(i);//用于worker 发消息
    setTimeout("timedCount()", 500);
}

timedCount();

If the worker is an external file, as referenced above, like other js not use html in the window, document, parent objects

Guess you like

Origin www.cnblogs.com/daimaxuejia/p/12468727.html