Edward Yang Edward Yang - 1 year ago 82
HTML Question

Elements created with JavaScript are not showing up when infinite loop is running

I have elements created with document.appendChild(); infinite loop.
If I have the infinite loop running after all the elements are created, it causes all the created elements to not show up, causing my website to look blank.

How do I go about fixing this issue?

Answer Source

In a browser, the DOM rendering and javascript engine run in the same thread. Meaning an infinite loop will block the DOM from rendering.

You need to use a setInterval() or requestAnimationFrame() to run your code asynchronously, giving the browser an opportunity to render the DOM.

EDIT: You said in the comments that you're using the infinite loop to check the state of radio buttons. That is unnecessary since the browser uses an event model. This means you can listen radio button change events and an event "handler" function can be called only when the state changes.