I’m trying to figure out how JavaScript’s event loop works. I think I understand the basics but want to make sure I’m getting it right.
My test code:
let processData = (callbackFunc) => {
callbackFunc("hello world");
};
let displayMessage = (message) => {
console.log(message);
};
processData(displayMessage);
setTimeout(() => {
console.log("timeout finished");
}, 0);
console.log("end of script");
What I think happens:
The processData function runs right away because it’s synchronous and doesn’t go into any queue. But setTimeout is async so it gets put in the callback queue. The callback queue only runs after all the main thread code is done, so the timeout runs last.
My questions:
- Am I understanding this correctly?
- What makes something async in JavaScript? Are there just certain built-in functions that are async?
- Is it possible to create your own async operations without using things like
setTimeout?
You’ve got the execution order right. The part you’re missing is that callbacks aren’t automatically async - it depends on what operation you’re using. In your example, processData runs synchronously because you’re calling the callback directly. But setTimeout’s callback gets queued because setTimeout is a Web API operation. The browser handles the timing, then queues the callback when it’s ready. To create async operations, you’d wrap existing async primitives in new functions - like making a Promise that uses setTimeout or fetch internally. The core async behavior still comes from browser APIs, but you can build more complex patterns on top. One more thing: the event loop takes completed async operations and moves their callbacks from Web API space into the task queue, not straight to execution.
yup, you got it! setTimeout and things like fetch go into the queue. for your own async ops, look into promises or async/await. good job on the understanding!
You’ve got it right. JavaScript doesn’t decide what’s async - the Web APIs do. Things like setTimeout, fetch, and DOM events get handled by the browser’s Web APIs, not the JS engine itself. When they finish, their callbacks go into the task queue. For making your own async stuff, you can use Promises with resolve/reject or async/await. But here’s the thing - you’ll always end up using built-in async primitives like setTimeout or Promise constructors. You can’t create truly async behavior without something the browser already handles asynchronously. Just one quick fix - there are actually multiple queues. The microtask queue (for Promises) has higher priority than the regular callback queue. But yeah, your basic understanding is solid.
This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.