JS implements multi-threading to solve unreliable/inaccurate timers

Why are timers unreliable

In the event loop execution mechanism, the asynchronous event will put the callback function into the message queue. After the macro task of the main thread is executed, the microtasks in the message queue will be executed sequentially. After the microtask is executed, it will return to execute the macrotask. Since there are a large number of tasks in the message queue, the execution time of other tasks will cause the delay of the timer callback function. If it is not processed, the delay will always be superimposed. When the running time is long, the difference will be very large.
So the timer is not fully guaranteed.

How to deal with it?

web Worker

JS in the browser is all single-threaded work. When some time-consuming work is performed on the front end, subsequent steps such as page rendering will wait, which will cause some pages to freeze and freeze, affecting user experience.
The emergence of webworker is to create a multi-threaded environment for js. The main thread creates a worker thread, which can hand over computationally intensive or high-latency tasks to the worker thread for execution. While the main thread is running, the worker thread is also running without interfering with each other. The main thread is responsible for UI interaction, so that the main thread will not be blocked. block.

Code

According to its own logic, the corresponding business can be processed in onmessage
index.js

// 创建work线程
const worker = new Worker('worker.js')
// 收到到消息
worker.onmessage =function(evt){
    
      
	// evt.data = 'worker.js :AAAAAAAAA'
    console.log('收到消息:返回的',evt.data)   
}
// 发送消息
worker.postMessage('AAAAAAAAA')

worker.js

	this.addEventListener('message', function (e) {
    
    
		// e.data = 'AAAAAAAAA'
	    this.postMessage('worker.js :'+e.data);
	}, false)
	// 监听错误
	this.addEventListener('error', function (e) {
    
     
	    console.error("收到消息",e)
	}, false);

Guess you like

Origin blog.csdn.net/lys20000913/article/details/130127407