Search code examples
javascriptmultithreadingweb-worker

parallelism in the browser


Am currently working on a project, were as the change event listener is fired, a content is updated in the browser.

 <html>
   <head>
   </head>
   <body>
       <input type="number" max="100" min="1" value="20" step="1" />
       <p>CHANGE THE SIZE OF THIS TEXT</p>
       <script>
        const input = document.querySelector("input");
        input.addEventListener("change", evt => {
            const p = document.querySelector("p");
            const { target } = evt;
            p.setAttribute("style", `font-size: ${target.value}px`);
        })
       </script>
   </body>
 </html>

The problem with this is that, let's say i take 3 seconds to change the value of the input element everything works fine, if i change the value of the input element very fast the effect does not show up in the HTMLParagraphElement ( it seems likes asynchronous event in the event loop executes concurrently ). So i thought of using webworkers but in webworkers we are not allowed to use DOMElement or DOMApis. Is there any way to allow this operations to execute simultaneously ?


Solution

  • I'm assuming that what you meant is that when you hold down the up/down arrows inside the input box, the text isn't changing size while you hold the buttons down.

    The issue actually doesn't have to do with concurrency but rather with the event that you chose to listen to. onChange only fires when the element loses focus (i.e. on mouse up in this case). Meanwhile, oninput fires immediately when the value changes. So in this situation you want to listen to the oninput event.

    Here is how you would do that: https://codepen.io/rzrzrz/pen/GBgLYr

    input.addEventListener("input", evt => { ... });