DEV Community

Cover image for Running while(true) in JS
Abhishek Raj
Abhishek Raj

Posted on

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 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 😇

Top comments (0)