Change values between 2 standar values, every second

Change values between 2 standar values, every second
0
#1

I want to change color between two standar colors ( from the colors array). How can i do that?
my code so far:

let colors = ["green", "red"];
setInterval(function(){
     div.style.backgroundColor = 'blue';
}, 1000);
#2

Let say you want it to be randomly, it will be like this:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

let colors = ["green", "red"];
setInterval(function(){
     div.style.backgroundColor = colors[getRandomInt(colors.length)];
}, 1000);

Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

If you don’t want it randomly, just access the desired color by index

let colors = ["green", "red"];
setInterval(function(){
     div.style.backgroundColor = colors[0]; // Green
}, 1000);
#3

hey,
you could do something like this:

let colors = ["green", "red"];
let num = 1;
setInterval(function(){
    document.body.style.backgroundColor = colors[num];
    num == 1 ? num-- : num++;
}, 1000);

num gonna be either 1 or 0

#5

Note if you can do this with CSS, do it with CSS; it’s easier to just define a keyframe then set the animation to loop constantly, and you can make it a lot smoother a lot easier.

let x = 0;
let colors = ["red", "green"]; 

setInterval(() => {
  div.style.backgroundColor = colors[x];
  x ^= 1;
}, 1000);

Edit: same as @orvalho said (for some reason my app didn’t show newer posts)

#6

thanks!
can you explain me how this line works though? x ^= 1

#7

It’s bitwise XOR (exclusive or). x ^ y is 0 if x and y match (in terms of bits), 1 if they don’t.

So if num is 1, 1 ^ 1 is 0. If num is 0, 0 ^ 1 is 1.

It’s an infix operator, works the same way as +, * etc. So like how a += 1 is the same as a = a + 1, num ^= 1 is the same as num = num ^ 1

#8

thanks! that was smart

#9

Note how @orvalho did it has the same result and is more readable and you probably shouldn’t do what I did (I used it a lot for oscillating between values in a thing I was doing recently, I kinda typed it without thinking).

Note this is much clearer & better:

num = 1 - num;
#10

how can i know which code to write?
I mean, should i only consider my code to be readable?
How do i know which “code” is better, faster, etc?
do you have some recomendations to tell me or a link to read about that?
Also which aspects should i take under consideration except “more readable” code ?

#11

In a few days/weeks/months time, if you look at the code, will you know what it does?

NB If it involves bitwise and you don’t have a specific reason for using it – ie you don’t fully understand it – as a rule, don’t use that code. When I said “Note this is much clearer & better” I just meant better than num ^= 1 from an understandable code PoV.

Clean Code by Robert Martin is also useful – overview here (arguably you only need an overview, not the whole book):