-1

I have this sample of code When i run updateBgColor() in js dev console of navigator the color is updating after function call finished. Could someone explain this behavior and how can i force updating the color before sleep(4000);

Note: In my process sleep(4000) will be replaced by long task that may take several seconds.

<html>
<head>
  <script>
      function sleep(milliseconds) {
        const date = Date.now();
        let currentDate = null;
        do {
          currentDate = Date.now();
        } while (currentDate - date < milliseconds);
      }
      function updateBgColor()
      {
          document.bgColor="green";
          sleep(4000);
      }
  </script>
</head>
<body></body>
</html>
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
  • Duplicate of [force DOM redraw with javascript on demand](https://stackoverflow.com/questions/16875690/force-dom-redraw-with-javascript-on-demand) – Guy Incognito Oct 07 '20 at 10:12
  • Also, you've tagged this with Ajax – hopefully the "long task" isn't a synchronous Ajax request? The problem goes away automatically if the Ajax call is asynchronous. – Guy Incognito Oct 07 '20 at 10:13
  • @GuyIncognito won't a long blocking task still be blocking even if it's made async? – evolutionxbox Oct 07 '20 at 19:18
  • @evolutionxbox I don't understand the question. "Blocking" and "async" are opposite concepts. – Guy Incognito Oct 07 '20 at 19:24
  • As most (if not all) browsers implement JS as single threaded, a function which blocks will still block even if made async. They're not total opposites. Quentin's answer is spot on. – evolutionxbox Oct 07 '20 at 19:27
  • Note that I'm talking about asynchronous vs synchronous Ajax calls, not just slapping an `async` keyword in front of a function. – Guy Incognito Oct 07 '20 at 19:34

1 Answers1

0

Could someone explain this behavior

Browsers don't repaint the DOM in the middle of JS functions. It lets them stack up multiple DOM changes and then repaint only when they are all done for efficiency.

how can i force updating the color before sleep(4000);

Don't put long-running, blocking code on the main event loop.

You might farm it out to a webworker instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335