Location>code7788 >text

JavaScript single-threading principle and asynchronous programming mechanism

Popularity:118 ℃/2025-04-16 22:35:18

JavaScript single-threading principle and asynchronous programming mechanism

Why is JavaScript single-threaded?

JavaScript is designed as a single thread, simply put it -The work in the browser can only be queued up one after another, and it is impossible to open more windows to catch fish at the same time.

Take a chestnut:

You click the button → The web page needs to pop a prompt → If the web page is still loading data → The web page has to pop a prompt, you have to wait for the loading →Single thread = Only do one thing at a time

Why is it designed like this?

  • Initially, the web page interaction was simple (filling the form, clicking the button), and a single thread was enough.
  • Avoid multi-threading fights (such as changing the state of the same button at the same time)

Advantages of single thread:

  • Simple development: Avoid complex problems such as data competition and deadlock in multi-threads.
  • Easy to debug: The execution order is clear and clear, which is easy to troubleshoot problems.
  • Suitable for I/O-intensive tasks: Most JS tasks (such as event processing, request response) do not require multi-core computing resources.

Disadvantages of single thread:

  • High risk of blockage: Once there are time-consuming operations (such as big data calculations, dead loops, etc.), the main thread will be stuck, resulting in the page being stuck or unresponsive.
  • Unable to utilize multi-core CPUs: In default mode, parallel computing cannot be performed, wasting the power of modern multi-core processors.

How to implement high concurrency and multi-threading in JavaScript?

Although JS is a single-threaded execution model, through the browser or provided mechanism, we can implement "Pseudo-concurrency"or "multi-threaded simulation", the main methods are as follows:

✅ Asynchronous operation (do something else first when loading)

  • principle: The task is suspended, the main thread is given up when waiting for resources, and the event queue mechanism is used to reschedule the execution after the task is completed.
  • Common ways
    • setTimeout / setInterval
    • Promise
    • async/await
    • Ajax / Fetch API

✅ Web Worker (open a small account to work secretly)

  • Enable an independent thread to run the JS script without affecting the main thread.
  • Suitable for large computing tasks, offline data preprocessing, etc.
  • Use with the main threadpostMessage() / onmessage
//
 const worker = new Worker("")
 ("Start Calculation")
  = (e) => {
   ("Subthread result:", )
 }
//
 onmessage = function (e) {
   // Perform intensive tasks
   let sum = 0
   for (let i = 0; i < 1e8; i++) sum += i
   postMessage(sum)
 }

✅ Worker Threads in

  • useworker_threadsThe module implements multi-threading capabilities on the backend, which is suitable for CPU-intensive scenarios.

✅ Task break (cut big jobs into small jobs and do them interspersedly)

  • userequestIdleCallbacksetTimeoutProcess data shards to reduce lag.

The difference between asynchronous and synchronous

Synchronous

  • The execution order is strict, and you must wait for the previous task to complete before the next one can be executed.
  • Block the main thread.
("A")
 ("button").click() // Block until click
 ("B")

Asynchronous

  • The background processs tasks, does not block the main thread, and notifies the results through callbacks or events.
("A")
 setTimeout(() => ("B"), 1000)
 ("C")
 // Output order: A -> C -> B

Understanding and use of Promise, async and await

Promise

  • Used to encapsulate an asynchronous operation to avoid callback hell.
  • There are three states:pending(Waiting),fulfilled(Completed),rejected(Rejected)
  • pass.then() / .catch()Chain processing results.
function fetchData() {
   return new Promise((resolve, reject) => {
     setTimeout(() => {
       const success = true
       success ? resolve("Data loading successfully") : reject("Failed")
     }, 1000)
   })
 }

 fetchData()
   .then((data) => (data))
   .catch((err) => (err))

async/await

  • yesPromisesyntax sugar, making asynchronous code write like synchronous code.
  • Only inasyncUsed in functions.
  • usetry/catchMore convenient to handle exceptions.
async function getData() {
   try {
     const data = await fetchData()
     ("Result:", data)
   } catch (err) {
     ("Error:", err)
   }
 }

 getData()

Summarize

Technology/Features describe
Single-threaded model JS defaults to only one main thread, and tasks are executed sequentially.
Asynchronous operation Do not block the main thread, execute callbacks through event queue
Web Worker Simulate multithreading in the browser, suitable for heavy tasks
Node WorkerThreads Multithreaded computing solution for the backend
Task splitting Split large tasks into small pieces, perform them in frames to reduce stress
Promise Manage asynchronous logic to avoid callback hell
async/await Make asynchronous code more like synchronization and improve readability

In short, a single thread is like a cashier at the cashier, but modern web pages use various methods to make the clerk quick and quick.