DEV Community

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

Posted on

3 1

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 😇

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay