JS is the event mechanism around

Survivor driver 2021-05-04 18:52:21
js event mechanism

as everyone knows ,js A single thread , Responsible for page drawing and user events, etc , That is what we usually understand UI Threads , For page rendering , Can only be updated on one thread , This is a consensus. , Otherwise, multiple threads update at the same time UI, This is incomprehensible . although android Of UI So do threads , however android It supports multithreading , and js It's just a single thread , It means that we can only do one thing at a time , Although there are asynchronous tasks , But that's just delaying execution .

Of course, in order to adapt to the development of the times ,js adopt web worker Supports multithreading capabilities , There's a Example

Here are some concepts :

Synchronization task

JS Functions that are immediately pushed into the execution stack and can be executed in the main thread . Tasks queued for execution on the main thread , Only the previous one has been executed , To perform the latter , The code is blocked , Sequential execution . It should be noted that ,click,dispatchEvent And so synthetic events are Synchronization task , Call the event handler synchronously . Please refer to the following links :

// The following output is 
// on click
// end
const App = () => {
return (
<div ref={(ref) => {
if(ref) {
}} onClick={() =>{
console.log('on click')
 Copy code 

Asynchronous task

If a function is called after Can't get the expected results right away So asynchronous tasks , The task is non blocking .

Every time you perform an asynchronous task , Will put the task into the corresponding task queue .

  • setTimeout setInterval
  • promise
  • dom event
  • Network request
  • ...

The event loop

js By waiting for the task queue , Perform tasks, deal with user events and page drawing continuously , Each event cycle is called once tick, Including fetching task execution from task queue , Clear the micro task queue , Page redraw ( It is not necessary to carry out ).

Macro task ( Browser initiated )

Execute the macro task and enter the macro task queue

  • I/O
  • dom event
  • setTimeout setInterval(web api) The browser has a timer module , The timer will not put the asynchronous task into the asynchronous queue until the execution time ,setTimeOut setInterval The delay is the time after which the callback function will be put into the task queue

Micro task (js Engine initiated )

Executing a micro task will enter the micro task queue of the current task , It will be cleared and executed before the next event . The advantage of micro task is high priority , But if you do micro tasks over and over again , It will delay the processing of the next event .

  • Promise.then .catch
  • MutationObserver
  • queueMicrotask Team functions as micro tasks


requestAnimationFrame It's also an asynchronous task , But it's special , Neither macro nor micro , It's in event Call before next repainting , That is, micro task , Before the next event . For details, see This . But every one of them eventloop It doesn't have to be redrawn , So in different browsers ,requestAnimationFrame The timing of implementation is different , This is the time to redraw standard .

Task queue

There is a demonstration effect demo latentflip.com/loupe


( picture source zhuanlan.zhihu.com/p/105903652


Code Here

Simulation event mechanism

console.log("--- task start ---");
setTimeout(() => {
console.log("macro task 1");
}, 0);
console.log("wait countdown");
new Promise((resolved, reject) => {
let time = Date.now();
console.log("countdown 500ms start");
while (Date.now() - time < 500) {}
console.log("countdown end");
.then((e) => {
console.log("micro task 1");
console.log("wait end");
queueMicrotask(() => {
console.log("micro task 2");
queueMicrotask(() => {
console.log("micro task 3");
console.log("---micro task end---");
console.log("---macro task start---");
setTimeout(() => {
console.log("macro task 2");
console.log("---macro task end---");
}, 0);
console.log("---task end---");
console.log("---micro task start---");
 Copy code 
 The output is as follows :
--- task start ---
wait countdown
countdown 500ms start
countdown end
wait end
---task end---
---micro task start---
micro task 1
micro task 2
micro task 3
---micro task end---
---macro task start---
macro task 1
macro task 2
---macro task end---
// It can be seen that promise.then It's a micro task The execution order of micro tasks is the same as that of joining the team 
// promise It's a synchronous mission Enter the execution stack to execute 
// setTimeout It's a macro task The order of execution is the same as the order of joining the team Later than micro task execution 
 Copy code 

simulation dom event

import "./styles.css";
const onClick = (type:string) => {
console.log(`${type} on click`)
Promise.resolve().then(e => {
console.log(`${type} micro task`)
setTimeout(() => {
console.log(`${type} macro task`)
}, 0);
export default function App() {
return (
<div className="App">
<h2> View the click event process </h2>
<div className="Parent" onClick={()=>{
<div className="Child" ref={(ref) => {
if(ref) {
console.log('---auto click---')
}}> Am I </div>
 Copy code 
 The page is loaded successfully. The result is as follows :
---auto click---
child on click
parent on click
child micro task
parent micro task
child macro task
parent macro task
// Active event synthesis and distribution , At this time two onClick It enters the execution stack as a synchronous event ,
// Two onClick In the same incident , So it will output two first on click
After clicking the button, the output is as follows :
child on click
parent on click
child micro task
parent micro task
child macro task
parent macro task
// Manual clicking is different , At this time two onClick They all enter the macro queue as asynchronous tasks 
// Two onClick Not in the same event , So the first one onClick Of promise Before the second onClick perform 
 Copy code 


In each event cycle , From the macro task queue Mission t perform , And then put Mission t The synchronization tasks in are executed in sequence , Asynchronous tasks enter the task queue , If it's a macro task , Enter the macro task queue , If it's a micro task , Enter the current micro task queue . next , After the stack is cleared , All tasks in the current micro task queue are executed , Then the browser calls according to whether to redraw the page requestAnimationFrame.

Reference resources

本文为[Survivor driver]所创,转载请带上原文链接,感谢

  1. Gallop workflow engine design series 01 process element design
  2. VUE移动端音乐APP学习【十六】:播放器歌词显示开发
  3. Vue Mobile Music App learning [16]: player lyrics display development
  4. jquery cookie
  5. jquery cookie
  6. 体面编码之JavaScript
  7. JavaScript for decent coding
  8. React17 系统精讲 结合TS打造旅游电商平台
  9. React17 system combined with TS to build tourism e-commerce platform
  10. 2021-05-04 hot news
  11. HttpSession对象与Cooike的关系 以及 Cookie对象构造函数问题
  12. gRPC-Web:替代REST的gRPC的Javascript库包
  13. The relationship between httpsession object and cooike and the construction of cookie object
  14. Grpc Web: a JavaScript library package to replace rest grpc
  15. Building reactive rest API with Java - kalpa Senanayake
  16. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  17. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  18. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  19. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  20. Vue.js比jQuery更容易学习
  21. Node.js的Reactor模式 与异步编程
  22. Vue. JS is easier to learn than jQuery
  23. Reactor mode of node.js and asynchronous programming
  24. 详解JavaScript中的正则表达式
  25. Explain regular expressions in JavaScript
  26. 详解JavaScript中的正则表达式
  27. Explain regular expressions in JavaScript
  28. JS: closure
  29. Write your own promise in promises / A + specification
  30. Analysis of the core mechanism of webpack from loader, plugin to egg
  31. On the import and export of webpack
  32. Interpretation of lodash source code (2)
  33. Hexo series (5) writing articles
  34. 有人用过JMeter或用HttpUnit写过测试吗????
  35. Has anyone ever used JMeter or written tests in httpUnit????
  36. JavaScript异步编程4——Promise错误处理
  37. Leetcode 1846. Reduce and rearrange the largest element of an array
  38. JavaScript asynchronous programming 4 -- promise error handling
  39. SQLite是一种经典的无服务器Serverless
  40. 通过Spring Boot Webflux实现Reactor Kafka
  41. SQLite is a classic server less
  42. Realization of reactor Kafka through spring boot Webflux
  43. Focus on the basic knowledge of JS
  44. Node.js与Spring Boot比较? - Ryan Gleason
  45. Compare node.js with spring boot- Ryan Gleason
  46. 「HTML+CSS」自定义加载动画【049】
  47. 「HTML+CSS」自定义加载动画【048】
  48. 「HTML+CSS」--自定义加载动画【047】
  49. "HTML + CSS" custom loading animation [049]
  50. "HTML + CSS" custom loading animation [048]
  51. "HTML + CSS" -- custom loading animation [047]
  52. 使用Akka实现Reactive DDD
  53. Prototype与JQuery对比
  54. Using akka to realize reactive DDD
  55. Comparison between prototype and jquery
  56. Please elaborate the diff algorithm of Vue
  57. On the combination of ecarts and Baidu map, in the Intranet environment to develop offline map, to achieve point, line, range value.
  58. 使用Slonik框架基于Node.js和PostgreSQL处理大量数据
  59. Using slonik framework to process large amount of data based on node.js and PostgreSQL
  60. Netflix使用React制作高性能电视用户界面