← JavaScript runtime

The call stack in one minute, and the other Shorts on JavaScript runtime

JavaScript runtime · 1-min Short

The call stack

Why one customer's support thread is a blank page.

Start the lesson
transcript

One customer's page went blank. The agent's fix froze it. Both come down to the call stack.

I open my support thread, and the page goes blank. Only yours? The console shows one line: RangeError, maximum call stack size exceeded.

This is the code that draws a thread. I wrote it. It draws a comment, then calls itself for each reply. Let me run it on a normal one first. While the deepest reply is being drawn, how many renderReplies calls are still running?

Ana's thread came from an import. Her first message names its own reply as its parent. So c1 draws c2, and c2 draws c1, forever. At about five thousand calls, Chrome stops the script.

Can you fix the crash? Done. I wrapped the loop in try and catch. If it fails, I retry with the same comment. Now my page is stuck. Same input, same calls. My retry never ends. Twenty seconds later, Chrome was still running it.

Remember which comments you have drawn, and skip one you have seen. c2 finds c1 already drawn and returns at once. Every comment draws once, and the stack empties. It loads now. Fix the cycle, not the error.

JavaScript runtime · 1-min Short

The event loop

Why the agent's search box shows results out of order.

Start the lesson
transcript

setTimeout with zero milliseconds does not run next. Your agent's code depends on that.

An agent wrote a search box. Type fast, and sometimes the results belong to an older query.

Before we explain anything, look at these four lines. In what order do they print?

The script runs top to bottom on the call stack. Line one logs A straight away.

setTimeout doesn't run the callback. It hands it to the browser's timer, outside JavaScript.

The promise callback goes to the microtask queue, and line four logs D. Once the timer expires, the browser puts its callback in the task queue.

The stack is empty, and two callbacks are waiting. Which one does the loop pick first?

Every microtask runs before the next task. C prints, then the loop takes the timer callback, and B prints last.

end of the collection

JavaScript runtime

2 of 6 lessons in this module have a Short.

Back to collections