How can js achieve multi-threading effect?
过去多啦不再A梦2017-05-19 10:28:22
First, let’s talk about the execution principle of JS: when the js engine executes js code, it is single-threaded, that is, there will only be one process executing JS code at the same time, and the callback functions are also executed one by one (in the order of events, not the code) Order). Asynchronous communication and timing in JS are implemented by another thread, independent of the js thread context. Taking JS timing operations as an example, when the JS engine executes the setTimeout(callbackFunction, 100) operation, it will notify the timing thread that I need 100 milliseconds of timing, and then the JS engine will enter the event loop. After 100 milliseconds, the timing engine adds an event that has expired to the event queue. The JS engine reads the time-out event from the queue and executes the callbackFunction. If multiple events are added to the event queue at the same time, the JS engine will only execute callbacks one by one. The same is true for asynchronous. The JS code initiates a communication request, the communication thread performs the communication operation, and adds the completion event to the event queue after the operation is completed. The JS engine takes the event from the queue and calls a callback to process the communication result. When the JS engine executes the callback function, it cannot respond to other events at the same time.
黄舟2017-05-19 10:28:22
JS's web worker can perform some large-scale operations on the background thread without blocking the main thread; it communicates with onmessage and the main thread through postmessage; but it has restrictions and cannot operate DOM and certain APIs; you can read the documentation for details.
黄舟2017-05-19 10:28:22
Javascript is threaded. If you want to achieve multi-threaded effects, you can consider node.js to achieve the goal through node events.
漂亮男人2017-05-19 10:28:22
If it is used in a browser, there is now a service worker that can run some js in the background, which is like opening an extra thread. I don’t know much about it, but you can find out if you need it