0

I'm using react js. I try to run the simple code:

setTimeout(() => {
       setTimeout(() => {
         const element = document.getElementById(‘circle’)
         element.style.backgroundColor = ‘red’
       }, 3000)
     }, 3000)

The CSS of 'circle' is just:

width: 100px;
height: 100px;
border-radius: 50%;
background-color: blue;
transition: background-color 2s;

I run the code and immediate change tab or minimize the screen, waiting more then 6 seconds and go back to the page and then the transition start. For some reason the transition not run if screen not in focus. Any help guys???

Chif
  • 830
  • 1
  • 7
  • 20
Nir Hanan
  • 1
  • 1
  • 2
    Hi Nir, on asking a question please provide a producible example, [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Side note: querying the DOM in react is often a bad practice, meaning - you may doing something wrong. – Dennis Vash Oct 27 '19 at 10:13
  • Possible duplicate of [How can I make setInterval also work when a tab is inactive in Chrome?](https://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome) – Aprillion Oct 27 '19 at 10:25

3 Answers3

1

The behavior you describe depending on the browser because inactive tabs have low priority execution.

While you performing a "JS Animation" you may want to use requestAnimation.

A better approach may use a "CSS Animation" with transition-delay.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

Use this code why are using Apostrophe mark in code.

    <script>
        setTimeout(() => {
               setTimeout(() => {
                 const element = document.getElementById('circle')
                 element.style.backgroundColor = 'red'
               }, 3000)
             }, 3000)
        </script>
M F L
  • 1
  • 2
0

Actually it is not really help me. The solution i made is to listen to 'focus' and 'blur' and stop any animations process and timers on blur and continue from last point at focus.

Nir Hanan
  • 1
  • 1