[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Execution_model [Back]  [Original]

- JavaScript | MDN

MDN Web Docs

View in English Always switch to English

JavaScript concurrency modelevent loop C Java

In this article

Runtime concepts

JavaScript

Visual representation

Stack, heap, queue [Stack, heap, queue]

Stack

Function frame

js
function foo(b) {
  var a = 10;
  return a + b + 11;
}

function bar(x) {
  var y = 3;
  return foo(x * y);
}

console.log(bar(7));

bar bar frame bar foo foo frame foo frame bar frame bar

Heap

Queue

JavaScript function function

Event loop

js
while (queue.waitForMessage()) {
  queue.processNextMessage();
}

queue.waitForMessage

Run-to-completion

C C

a script taking too long to run

Adding message

setTimeout 0setTimeout

setTimeout

js
const s = new Date().getSeconds();

setTimeout(function () {
  // prints out "2", meaning that the callback is not called immediately after 500 milliseconds.
  console.log("Ran after " + (new Date().getSeconds() - s) + " seconds");
}, 500);

while (true) {
  if (new Date().getSeconds() - s >= 2) {
    console.log("Good, looped for 2 seconds");
    break;
  }
}

Zero delay

callback function 0 0 setTimeout this is just a message setTimeout

js
(function () {
  console.log("this is the start");

  setTimeout(function cb() {
    console.log("this is a msg from call back");
  });

  console.log("this is just a message");

  setTimeout(function cb1() {
    console.log("this is a msg from call back1");
  }, 0);

  console.log("this is the end");
})();

// "this is the start"
// "this is just a message"
// "this is the end"
// "this is a msg from call back"
// "this is a msg from call back1"

Several Runtime communicating together

Web worker cross-origin iframe postMessage message

Never blocking

I/O IndexedDB XHR

exceptions alert XHR


Web Proxy Viewer  |  New URL  |  Original Page