5

Running while(true) in JS

 2 years ago
source link: https://dev.to/abhishekraj272/running-whiletrue-in-js-1aoh
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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 😇


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK