Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for repaint in Javascript

I am trying to run some code after I change the background of an element. I'd like to run the code after the background is changed visually, not just internally. Thus I'd like to wait for a repaint. I tried doing this using rAF, but that does not seem to be the correct way, because the code gets executed before the background color is changed visually (talking about milliseconds though).

I tried to achieve my goal with the following code (without luck):

  requestAnimationFrame(() => {
    document.getElementsByTagName("body")[0].style.backgroundColor =
      "rgb(0, 75, 75)";
      requestAnimationFrame(() => {
        socket.emit("notify-black");
      });
  });

What would be the correct way of waiting for the repaint?

like image 654
Bram Vanbilsen Avatar asked Jul 25 '26 06:07

Bram Vanbilsen


1 Answers

requestAnimationFrame will run its callback just before the next repaint. Put the code you want to run in a setTimeout inside that, since the timeout callback will run almost immediately after the repaint finishes.

You can also use document.body instead of document.getElementsByTagName("body")[0]:

requestAnimationFrame(() => {
  document.body.style.backgroundColor = "rgb(0, 75, 75)";
  requestAnimationFrame(() => {
    setTimeout(() => {
      socket.emit("notify-black");
    });
  });
});

Live demo, using alert (which blocks) instead of socket.emit:

requestAnimationFrame(() => {
  document.body.style.backgroundColor = "rgb(0, 75, 75)";
  requestAnimationFrame(() => {
    setTimeout(() => {
      alert("notify-black");
    });
  });
});

Another example code that takes a screenshot using html2canvas. Open up example.com, open your console, and run the following:

const script = document.body.appendChild(document.createElement('script'));
script.src = 'https://html2canvas.hertzen.com/dist/html2canvas.js'
script.onload = () => {
  requestAnimationFrame(() => {
    document.body.style.backgroundColor = "rgb(0, 75, 75)";
    requestAnimationFrame(() => {
      setTimeout(() => {
        html2canvas(document.querySelector("body")).then(canvas => {
          document.write('<img src="'+canvas.toDataURL("image/png")+'"/>');
        });
      });
    });
  });
};
like image 62
CertainPerformance Avatar answered Jul 26 '26 21:07

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!