JS call stack


call stack

JavaScript is a single-threaded language, which means it has only one call stack, so it can only do one thing at a time. If we run to a function, it will put it on top of the stack. When returning from this function, the function is popped off the top of the stack, which is what the call stack does.

1  function multiply(x, y) {
2       return x * y;
3     }
4  function printSquare(x) {
5       var s = multiply(x, x);
6       console.log(s);
7     }
8     printSquare(5);



event loop

Introduce link:




  • macro-task (macro task): including the overall code script, setTimeout, setInterval
  • micro-task: Promise, process.nextTick



After entering the overall code (macro task), start the first loop. Then execute all the microtasks. Then start from the macro task again, find that one of the task queues has been executed, and then execute all the micro tasks.

 1 setTimeout(function() {
 2     console.log('setTimeout');
 3 })
 5 new Promise(function(resolve) {
 6     console.log('promise');
 7 }).then(function() {
 8     console.log('then');
 9 })
11 console.log('console');
  • First enter the overall code (macro task)
  • When SetTimout is encountered, its callback function console.log Join the Event Queue of the macro task
  • meetnew Promiseexecute, will.then is added to the microtask
  • meetconsole.log execute
  • The entire script code (macro task) has been executed at this time, and then check the micro task and find that there is a .then micro task, execute it
  • The first round of macro code has been executed, and the second round has begun. Check the Event Queue of the macro task and find thatsetTimeout, execute him.