I once spent hours debugging something that made no sense. The code looked correct. The logic was simple. But the console logs were appearing in a strange order. Something like this: Promise 𝗿𝗲𝘀𝗼𝗹𝘃𝗲𝗱 Then 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁 Then another log I expected earlier. That’s when I discovered something many JavaScript developers overlook: Not all async tasks are treated the same. Some go to the 𝗺𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗾𝘂𝗲𝘂𝗲. Some go to the 𝗺𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗾𝘂𝗲𝘂𝗲. And JavaScript always clears microtasks first before moving to the next macrotask. That’s why: Promises, 𝗾𝘂𝗲𝘂𝗲𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸, 𝗠𝘂𝘁𝗮𝘁𝗶𝗼𝗻𝗢𝗯𝘀𝗲𝗿𝘃𝗲𝗿 run earlier. While things like: 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁, 𝘀𝗲𝘁𝗜𝗻𝘁𝗲𝗿𝘃𝗮𝗹, 𝗗𝗢𝗠 𝗲𝘃𝗲𝗻𝘁𝘀 wait for the next event loop cycle. Once I understood this, a lot of 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝘀 𝘄𝗲𝗶𝗿𝗱 moments stopped being weird. They were just the event loop doing exactly what it was designed to do. Sometimes the bug isn’t in the code. It’s in our 𝗺𝗲𝗻𝘁𝗮𝗹 𝗺𝗼𝗱𝗲𝗹 of how the runtime works. #JavaScript #EventLoop #FrontendEngineering #SoftwareEngineering
Exactly! The moment you grasp the event loop, a lot of those mysterious async behaviors suddenly make sense.
sometimes the problem isn’t what we wrote, it’s how we’re thinking about what we wrote. Sheharyar K.