Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8652

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T03:08:08+00:00 2024-11-28T03:08:08+00:00

Quiz📣: How Well Do You Understand Asynchronous JavaScript?

  • 60k

Over the last few weeks, we had a lot of discussions on asynchronous JavaScript and patterns we use in our projects to build performant apps. It resulted in an article – 4 tips on writing better async/await code. Besides practical aspects like asynchronous coding patterns and best practices, one of the discussed topics was the importance of understanding how JavaScript handles asynchronous code under the hood.

Asynchronous code is passed to wait in one of the queues and executed whenever the call stack is empty. Tasks in the queues and call stack are coordinated by the event loop – the key mechanism used by JavaScript to avoid blocking the main thread. Learn more about it here.

We've collected 4 interesting examples of code (it looks like 4 is our favorite number 😉) that will help you test your knowledge of event loop and JavaScript asynchronous execution flow. Let's start ⏬

1. Which Queue Is Executed First?

Before diving deep into the event loop, call stack, and tasks, let's begin with a little warm-up question.

Not all queues were created equal. Knowing that setTimeout() callback is pushed to the task queue, and then() callback to the microtask queue, which one do you think will log first?

// Task queue  setTimeout(() => console.log('timeout'), 0)  // Microtask queue  Promise.resolve().then(() => console.log('promise')) 
Enter fullscreen mode Exit fullscreen mode

Show the answer 👇

promise  timeout 
Enter fullscreen mode Exit fullscreen mode

The tasks scheduled in the task queue will run first. But wait, how come the output logged from the setTimeout() callback appears second in our example?

In each iteration, the event loop will run the oldest initially existing task in the task queue first, and all the microtasks in the microtask queue second. When the event loop starts its first iteration, the task queue contains only one task – the main program script run. The setTimeout() callback is added to the task queue during the first iteration and will be queued from tasks only during the next iteration.

To better understand these mind-blowing concepts, check this animated diagram by Jake Archibald.

2. What Is the Output of the Code Below?

To answer this question, you need to be familiar with the concepts like synchronous vs. asynchronous code order of execution and how the event loop is running tasks.

Equally important, you also need to know which code runs synchronously and which asynchronously. Hint: not all Promise-related code is asynchronous. 🤯

There are four console.log() calls below. What will be logged in the console and in which order?

let a = 1  setTimeout(() => {     console.log(a) //A     a = 2 }, 0)  const p = new Promise(resolve => {     console.log(a) // B     a = 3     resolve() })  p.then(() => console.log(a)) // C  console.log(a) // D 
Enter fullscreen mode Exit fullscreen mode

Show the answer 👇

/* B */ 1 /* D */ 3 /* C */ 3 /* A */ 3 
Enter fullscreen mode Exit fullscreen mode

The code inside the new Promise executor function runs synchronously before the Promise goes to a resolved state (when resolve() is called). For this reason example code logs 1 and sets variable a value to 3.

The variable value remains unchanged in all further console.log()calls.

3. In What Order Will Letters Be Logged?

How do DOM events fit in the event loop task handling mechanism? What we have here is a div container containing a button element. Event listeners are added to both the button and the container. Since the click event will bubble up, both listener handlers will be executed on a button click.

<div id="container">   <button id="button">Click</button> </div> 
Enter fullscreen mode Exit fullscreen mode

What is the output after button click?

const    container = document.getElementById('container'),   button = document.getElementById('button')  button.addEventListener('click', () => {   Promise.resolve().then(() => console.log('A'))   console.log('B') })  container.addEventListener('click', () => console.log('C')) 
Enter fullscreen mode Exit fullscreen mode

Show the answer 👇

B A C 
Enter fullscreen mode Exit fullscreen mode

No surprise here. The task of dispatching click event and executing handler will be invoked via the event loop, with synchronous code logging first and then() callback logging second. Next, the event bubbles up and the container event handler is executed.

4. Will the Output Change?

The code is the same as in the previous example, with a small addition of button.click() at the end. It is a weird UI design pattern where the button is clicked automatically. Do you think it's a game-changer or logging order stays the same? 🤔

const    container = document.getElementById('container'),   button = document.getElementById('button')  button.addEventListener('click', () => {   Promise.resolve().then(() => console.log('A'))   console.log('B') })  container.addEventListener('click', () => console.log('C'))  button.click() 
Enter fullscreen mode Exit fullscreen mode

Show the answer 👇

B C A 
Enter fullscreen mode Exit fullscreen mode

The strings are indeed logged in different order. button.click() is making all the difference, sitting at the bottom of the call stack and preventing microtask queue tasks from executing. Only after the call stack is emptied, () => console.log('A') will be queued from the microtasks.

Feel free to share your mind-boggling async & event loop related code examples in the comments ✍️. Don't forget to ❤️ and follow for more web dev content.

javascriptprogrammingquizwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers
  • Author

    Refactoring for Efficiency: Tackling Performance Issues in Data-Heavy Pages

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.