Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript, why doesn't the below code exit the loop?

let a = true;
setTimeout(() => {a = false}, 1000)
while(a){console.log(a)}
like image 516
c137 Avatar asked Mar 02 '21 13:03

c137


People also ask

How do you exit a loop in JavaScript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

Can you return out of a for loop JavaScript?

Yes, return stops execution and exits the function. return always** exits its function immediately, with no further execution if it's inside a for loop.

Is while loop blocking in JavaScript?

The issue is that once you go into the spin wait in the while() loop, NO other Javascript can execute. So, the timer that wants to change the value of the done variable cannot execute. Thus, the while loop condition can never change and thus it is an infinite loop.

How do you break a function in JavaScript?

Using return to exit a function in javascript Using return is the easiest way to exit a function. You can use return by itself or even return a value.

How to exit a loop in JavaScript?

For example, you may want to stop iterating through an array of items as soon as you find a specific element. TL;DR: use break to exit a loop in JavaScript. This tutorial shows you how to terminate the current loop in JavaScript and transfer control back to the code following the loop.

What are loops in JavaScript?

Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true or false when analysed. A loop will continue running until the defined condition returns false.

How to use break to exit from functions in JavaScript?

Using break to exit from functions in javascript is a less traditional way compared to using return. Break is mostly used to exit from loops but can also be used to exit from functions by using labels within the function. While try and catch are usually used for fetching data, it can also be used to exit a function.

How do you exit a loop in a catch block?

Since there is no piece of code in catch block, it will simply exit the loop - which is what we intended to achieve in the first place. This is yet another unconventional way to exit a function in javascript. All the three javascript exit functions, throw, break, and return are fully supported by all the browsers.


3 Answers

Let's see this step by step (if this was executed in browsers) :-

let a = true;
setTimeout(() => {a = false}, 1000)
while(a){console.log(a)}
  • let a = true; : You initialized a new variable a to true;

  • setTimeout(() => {a = false}, 1000) : You have told the browser's setTimeout Web API to execute a callback (() => {a = false}) in which we set a to false after minimum of 1 second. Minimum because that callback will not execute unless the JavaScript execution stack (This is where all your JS code is actually executed synchronously) is empty. This callback after 1s gets placed in an event queue and is dequeued from there only when the JavaScript execution stack is empty.

  • while(a){console.log(a)} : This will execute synchronously and block the main thread (where the execution stack is) since a is always true. Our main thread getting blocked means the completion of this operation is too expensive (makes sense since it's infinite logging) and so the JavaScript execution stack couldn't ever be free for any callback available in the event queue. That means () => {a = false} even though available in the event queue will never get a chance to be dequeued and run in our JavaScript execution stack.

The browser's Web API, this JavaScript execution stack and the event queue together forms our event loop for browsers.

JavaScript is single-threaded (remember main thread ?) synchronous language. All the asynchronous behaviour that you see in your web apps or servers is because of the other parts which form the event loop.

Also this is a simplified picture of it. There are more divisions to the event queue but that's beyond the scope of this question.

like image 52
Lakshya Thakur Avatar answered Nov 15 '22 23:11

Lakshya Thakur


Because JS is single threaded, setTimeout will run after 1000 ms when the thread is not busy. Since this while loops blocks the thread, the callback of setTimeout has no time to run and thus a stays true forever.

You can find more details on this topic here.

like image 45
Wendelin Avatar answered Nov 16 '22 00:11

Wendelin


setTimeout is asynchronous function, the provided callback will be executed only when the javascript call stack will be empty. As we have "while(true)" condition, it will always be executing something => call stack will never be empty => setTimeout callback will never be executing. For more info, read about JavaScript Event Loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

like image 36
Pavlov Serhiy Avatar answered Nov 15 '22 23:11

Pavlov Serhiy