Running while(true) in JS

You must be wondering this guy is MAD, we can’t run while/for loop synchronously client side in javascript, it will block the main thread and will FREEZE the page.

Well, it is possible to run it but not a good way to do it and might introduce some bug…


This content originally appeared on DEV Community and was authored by Abhishek Raj

You must be wondering this guy is MAD, we can't run while/for loop synchronously client side in javascript, it will block the main thread and will FREEZE the page.

Well, it is possible to run it but not a good way to do it and might introduce some bugs in your program.

Web Worker

Web Worker runs in a single thread isolated from the main thread, so you can run any synchronous operation without blocking the thread.

You can run the loop in Web Worker and send the send the data from Web Worker to Main Thread using postMessage method. It will run as good as main thread.

You can try it in the below code snippet

Note: Running synchronous loop is not advised in browser, unless there is a such requirement.

Connect Me @ Linkedin, Github, Twitter, Youtube 😇


This content originally appeared on DEV Community and was authored by Abhishek Raj


Print Share Comment Cite Upload Translate Updates
APA

Abhishek Raj | Sciencx (2021-12-18T11:37:53+00:00) Running while(true) in JS. Retrieved from https://www.scien.cx/2021/12/18/running-whiletrue-in-js/

MLA
" » Running while(true) in JS." Abhishek Raj | Sciencx - Saturday December 18, 2021, https://www.scien.cx/2021/12/18/running-whiletrue-in-js/
HARVARD
Abhishek Raj | Sciencx Saturday December 18, 2021 » Running while(true) in JS., viewed ,<https://www.scien.cx/2021/12/18/running-whiletrue-in-js/>
VANCOUVER
Abhishek Raj | Sciencx - » Running while(true) in JS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/12/18/running-whiletrue-in-js/
CHICAGO
" » Running while(true) in JS." Abhishek Raj | Sciencx - Accessed . https://www.scien.cx/2021/12/18/running-whiletrue-in-js/
IEEE
" » Running while(true) in JS." Abhishek Raj | Sciencx [Online]. Available: https://www.scien.cx/2021/12/18/running-whiletrue-in-js/. [Accessed: ]
rf:citation
» Running while(true) in JS | Abhishek Raj | Sciencx | https://www.scien.cx/2021/12/18/running-whiletrue-in-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.