New understanding and simple to use multi-threaded for H5

Because JavaScript determine the characteristics of single-threaded JavaScript language is a language, but sometimes we need to use multiple threads, such as a lot of computing time. H5 multi-threaded for this purpose adds.

Here I am using JavaScript to achieve the famous Fei Bola and the number of columns, and when I return to that position where the numbers in an input box, the first digit numeric value.

Relationship between the main thread and the thread points:

1, when not in use multithreading
HTML

<input type="text" placeholder="数值" id="number">
<button id="btn">计算</button>

JavaScript

// 1 1 2 3 5 8  ....   f(n) = f(n-1) + f(n-2)
    function fibonacci (n) {
        return n<=2 ? 1 : fibonacci(n-1) + fibonacci(n-2)  //递归调用
    }
    var input = document.getElementById('number')
    document.getElementById('btn').onclick = function () {
        var number = input.value
        var result = fibonacci(number)
        alert(result)
    }

Without the use of multithreading when we enter a larger value, due to the recursive call is computationally intensive and will result in an inoperable state page can only wait for the completion of the calculation users can interface

2, using the new multi-threading method H5

var input = document.getElementById('number')
    document.getElementById('btn').onclick = function () {
        var number = input.value

        //创建一个worker对象
        var worker = new Worker('worker.js')
        //绑定接受消息的监听
        worker.onmessage = function (event) {
            console.log('主线程接受分线程返回的数据:'+event.data)
            alert(event.data)
        }

        //向分线程worker.js发送消息
        worker.postMessage(number)
        console.log('主线程向分线程发送数据:'+number)
    }

Sub-thread worker.js

function fibonacci(n) {
    return n<=2 ? 1 : fibonacci(n-1) + fibonacci(n-2)
}

var onmessage = function (event) {
    var number = event.data
    console.log('分线程接收到了主线程发送的数据:'+number)
    //计算
    var result = fibonacci(number)
    postMessage(result)
    console.log('分线程向主线程返回数据:'+result)
}

It may be implemented when a user inputs a large value, calculating a main sub-thread thread unaffected so that the user can operate (block change input operation) to the page by fractional thread.

Multithreading shortcomings:

  • Not yet supported by all browsers.
  • Sub-thread (worker.js) inside the code can not be operated on the DOM (sub-thread global object because not Windows).
  • Can not cross-domain loading js.
  • Due to the exchange of data between the main thread and the thread so slow min.

Multithreading will complain locally run chorem browser, so use localhost in the form of test access path

Guess you like

Origin www.cnblogs.com/yuanchao-blog/p/10980196.html