JavaScript Interview Questions 21-25 (Timers, DOM, Virtual DOM, Events)
Welcome to Part 5 of our JavaScript interview series. In the previous lessons, we focused heavily on the logic and syntax of the language itself. Now, we are moving into how JavaScript interacts with the environment around it—specifically, the browser and time.
These questions are crucial for frontend development roles. We will look at how to schedule code to run later, how JavaScript "sees" and modifies HTML via the DOM, why modern frameworks use a "Virtual" DOM, and how mouse clicks travel through your web page. Let's dive in.
21. What are JavaScript timers (setTimeout, setInterval)?
JavaScript provides two native functions to handle time-based execution: setTimeout and setInterval. Since JavaScript is single-threaded, these functions allow us to offload tasks to be executed in the future without freezing the browser.
- setTimeout(callback, delay): Executes a function once after a specified delay (in milliseconds).
- setInterval(callback, delay): Executes a function repeatedly, waiting for the specified delay between each execution.
Analogy:
setTimeout is like an oven timer. You set it for 10 minutes, and it dings once when the time is up.
setInterval is like a metronome or a heartbeat. It ticks over and over again at a steady rhythm until you stop it.
console.log("1. Start");
// setTimeout: Runs once after 1 second (1000ms)
setTimeout(() => {
console.log("2. This runs once after delay");
}, 1000);
// setInterval: Runs every 2 seconds
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log("3. Interval tick: " + count);
// Safety valve: stop after 3 ticks so this example doesn't run forever
if (count >= 3) {
clearInterval(intervalId);
console.log("4. Interval stopped");
}
}, 2000);
console.log("5. End of script (timers are running in background)");
Sample Output:
1. Start
5. End of script (timers are running in background)
2. This runs once after delay
3. Interval tick: 1
3. Interval tick: 2
3. Interval tick: 3
4. Interval stopped
22. What is the difference between setTimeout and setInterval?
While both function similarly by taking a callback and a time in milliseconds, their behavior regarding repetition and cancellation is distinct.
| Feature | setTimeout | setInterval |
|---|---|---|
| Frequency | Executes once. | Executes repeatedly. |
| Cancellation | clearTimeout(id) | clearInterval(id) |
| Use Case | Delaying an animation, showing a notification, API timeout. | Polling a server, countdown clocks, carousels. |
Tip: In modern React (or other framework) development, you must be careful to clear these timers when a component "unmounts" (disappears from the screen). If you don't, setInterval will keep trying to update a component that no longer exists, causing memory leaks and errors.
23. What is the DOM in JavaScript?
DOM stands for Document Object Model. It is an interface (API) that treats your HTML document as a tree structure where each node is an object representing a part of the document (like a <div>, a <p>, or text).
JavaScript uses the DOM to act as a bridge to the HTML. It allows JS to change the structure, style, and content of the webpage dynamically.
Analogy: Think of HTML as the blueprints for a house. The DOM is a 3D holographic projection of that house. JavaScript is the architect who can reach into the hologram, grab a window, and move it, or paint a wall blue instantly. The moment the hologram changes, the real house updates.
// HTML assumption: <div id="app"><h1>Hello</h1></div>
// 1. Accessing an element
const appDiv = document.getElementById('app');
// 2. Creating a new element
const newParagraph = document.createElement('p');
newParagraph.textContent = "I was added by JavaScript via the DOM!";
// 3. Modifying styles
newParagraph.style.color = "purple";
newParagraph.style.fontWeight = "bold";
// 4. Appending (adding) it to the tree
appDiv.appendChild(newParagraph);
// The user now sees the new text on the screen immediately.
24. What is the difference between the DOM and the Virtual DOM?
The Real DOM is powerful but slow when it comes to layout updates. Every time you change something, the browser has to recalculate CSS, layout, and repaint the screen. If you change 10 things, it might repaint 10 times.
The Virtual DOM (used by libraries like React) is a lightweight JavaScript copy of the Real DOM. It is not visible on the screen.
How Virtual DOM works:
- When data changes, a new Virtual DOM tree is created.
- This new tree is compared (diffed) with the previous Virtual DOM tree.
- The library calculates the minimum number of changes needed.
- It updates the Real DOM in one single batch operation.
Analogy: Imagine you want to rearrange furniture in a room.
Real DOM: You physically move the couch. Then you decide you don't like it, so you move it back. Then you move the table. It is heavy, slow, and tiring work.
Virtual DOM: You sketch the room on a piece of paper. You erase the couch, draw it somewhere else. Erase it again. Draw the table. Once the sketch looks perfect, you go into the room and move the furniture exactly once to match the sketch.
// Real DOM interaction (Direct & Heavy)
document.getElementById('item1').innerHTML = "Updated";
document.getElementById('item2').innerHTML = "Updated";
// Browser might repaint twice
// Virtual DOM interaction (React style - Abstracted)
// 1. State changes
// 2. React compares virtual tree
// 3. React updates Real DOM in one batch
const element = <div>
<h1>Hello, world</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>;
25. What is event bubbling and event capturing?
These terms describe the "propagation" (flow) of events through the DOM tree. When you click a button inside a div, you aren't just clicking the button; you are also clicking the div, the body, and the html document.
- Event Bubbling (Default): The event starts at the target element (the button) and bubbles UP to the ancestors (Button → Div → Body). Most event listeners listen to this phase by default.
- Event Capturing (Trickling): The event starts at the top (Window) and trickles DOWN to the target (Window → Div → Button). This rarely used unless specifically requested.
Analogy: Imagine dropping a stone into a pond.
Bubbling: The bubbles rise from the bottom (the specific element) up to the surface.
Capturing: Like a diver diving from the surface down to the bottom to find the stone.
// HTML Structure:
// <div id="parent">
// <button id="child">Click Me</button>
// </div>
const parent = document.getElementById("parent");
const child = document.getElementById("child");
// Bubbling (Default behavior, 3rd argument is false)
parent.addEventListener("click", () => {
console.log("Parent Clicked!");
}, false);
child.addEventListener("click", (event) => {
console.log("Child Clicked!");
// Optional: stop bubbling up
// event.stopPropagation();
}, false);
// Output if you click the Child button:
// "Child Clicked!"
// "Parent Clicked!" <-- The event bubbled up to the parent
Congratulations! You have now covered 25 fundamental JavaScript questions. From the basic building blocks of data types to the complex behavior of the DOM and Event Loop.
Remember, technical interviews are not just about memorizing answers. They are about communication. Using these analogies (like the "oven timer" or the "furniture sketch") shows that you don't just know the code, you understand the concept. Keep practicing, stay calm, and good luck!