1. What are processes and threads

  • Process: can be understood as a program (browser opens a page to open a process)

  • Thread: a person who performs specific tasks in a program

A process can contain many threads, and a thread can only do one thing at a time

2. Synchronous and asynchronous

  • Synchronous programming: to do one thing at a time and not be able to do the next until the last thing is done. “Single-threaded”

  • Asynchronous programming: If the last event is not completed, the next event can proceed to “multi-threaded, single-threaded EventLoop mechanism…”

Asynchronous programming in JS

  • “Microtasks”

    • Ajax “HTTP Web Request”

    • promise

    • requestAnimationFrame

  • “Macro task”

    • The timer

    • Async/await “generator”

    • event

Tips JS is single-threaded

    1. Most of JS is synchronous programming
    1. However, it is possible to achieve asynchronous effects based on a single-threaded EventLoop

4. Browsers are multi-threaded. When you open a page, the browser will allocate many threads to handle several things at once

  • GUI rendering thread: Renders the page from top to bottom

  • JS engine (rendering) thread: Single JS thread because this is the only thread the browser will open up to execute JS code

  • HTTP Network request thread: load resource file or some data

  • Timer monitoring thread: Monitors whether the timer reaches the time

  • DOM event listener thread: Listens for DOM event triggering

5. EventLoop in JS

Exercise 1

setTimeout(() = > {
    console.log(1)},20)
console.log(2)

setTimeout(() = > {
    console.log(3)},10)
console.log(4)
console.time('AA') // Evaluation process execution time - start

for(let i = 0; i < 90000000; i++) {

}
console.timeEnd('AA') // Evaluation procedure execution time - end
console.log(5)
setTimeout(() = > {
    console.log(6)},8)
console.log(7)

setTimeout(() = > {
    console.log(8)},15)
console.log(9)
Copy the code

Exercises 2

setTimeout(() = > {
    console.log(1)},0)
console.log(2)
while(1) {
    // the main thread handles this thing all the time. The main thread can never do anything else
}
console.log(3)
setTimeout(() = > {
    console.log(4)},10)
console.log(5)
Copy the code
setTimeout(() = > {
    console.log(1)},0)
console.log(1)
console.log(a) // Throwing an exception will only affect the execution of the following tasks, but the tasks already placed in the EventQueue will continue to execute
setTimeout(() = > {
    console.log(2)},20)
Copy the code