Diego
Diego

Reputation: 964

Change the background of a circle periodically with css

I have 3 circles created with CSS.

I want to change the color of each circle every 3 seconds.

3 Seconds -> 1 Circle Color goes Orange
6 Seconds -> 2 Circle Color goes Orange
9 Seconds -> 3 Circle Color goes Orange
12 Seconds -> 1,2,3 Circle Color goes White

15 Seconds -> 1 Circle Color goes Orange
18 Seconds -> 2 Circle Color goes Orange
21 Seconds -> 3 Circle Color goes Orange
24 Seconds -> 1,2,3 Circle Color goes White

This is the loop. The problem I am having is that at 12 seconds not all of the circles go white. I am using the set Interval function for doing this.

this.boton1 = function(){
  var container = document.getElementById('circle1');
  container.style.background = '#FF7700';
};  

this.boton4 = function(){
  var container = document.getElementById('circle1');
  container.style.background = '#FFFFFF';
};

setInterval(boton1,3000);
setInterval(boton4,12000);

I am guessing I am managing wrong this with the set Interval. I have a DEMO HERE showing the results.

Thanks in advance

Update

In case someone need the solution. Here is the DEMO update

Upvotes: 1

Views: 873

Answers (1)

unconnected
unconnected

Reputation: 1011

The trouble is that you are using setInterval. It means that every 3 seconds circles go orange. But 12 % 3=0. And no one knows what will act the first setInterval(..,12000) or setInterval(..,3000). Change 12000 to 12500 or, imho, use setTimeout(sample,3000) where sample like this

function sample(){
  counter++;
  if (counter % 4 ==0){
    //circles go white
  } else {
    //circles go orange
  }
  setTimeout(sample,3000);
}

Upvotes: 1

Related Questions