H5 new features -WebWorker

WebWorker is H5 in the new API, we can easily use this API to create a background thread, webworker longer commonly used in the execution of those events takes a lot of logic or calculation cycle, to avoid the occurrence of suspended animation page.

  JavaScript language uses single-threaded model, that is, all tasks can only be done on a thread, only one thing.

  Web Worker role is to create a multi-threaded environment for JavaScript, the main thread creates Worker threads, some of the tasks assigned to the latter by, while work on the main thread, Worker are running in the background, the two non-interfering. Worker threads wait until after the completion of the task, and then return to the main thread. The advantage is that some computationally intensive tasks, the burden is Worker thread, the main thread will be very smooth.

1 Web Worker use issues that need attention:

  (1). Homologous restriction
  (2) DOM restrictions:. Worker threads can not access the page where the main thread DOM object, nor can document, window, parent objects. But the worker thread can access the navigator, location target
  (3) communication links:. Worker thread and the main thread is not in the same environment, it can not communicate directly, only through the completion of the message
  (4) script restrictions:. Worker threads can not execute alert (), confirm () methods
  . (5) file limits: worker thread can not read the local file system that is not open the machine (file: //), must come from network

 

2. Basic Usage

(1) the main thread:

// Create a Worker Thread
 var worker = new new Worker ( 'test.js'); // parameter is the script file Address
onmessage property
  onmessage property represents an event handler, when the Worker thread returns the message is called, its grammatical structure is:
Worker线程.onmessage = function(e){
...
};
postMessage () method
the postMessage () method for transmitting a message to the Worker Thread internal scope, structure syntax is:
worker thread .postMessage (the Message) 
// the Message parameter can be any type of data
terminate()
Behavior terminate () method used to terminate the Worker, the grammatical structure is:
worker thread .terminate ()
 
(2) worker thread
Worker internal thread has a monitor function, event monitor message, its grammatical structure is:
self.addEventListener('message',function(e){
  ....
});
postMessage () method
the postMessage () method for transmitting a message to the main thread:
this.postMessage(message)
close () method
close () method is used to close itself in ah Worker Thread, grammatical structure which is:
this.close() //或者 
self.close()

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

Guess you like

Origin www.cnblogs.com/codexlx/p/12562751.html