I am trying to make my background color different each time when the button is clicked and I don’t want to get the same color in a row so I did a check, if the current value is the same as previous value, then get the value again and if current value is different to previous value then return the value, but there is a problem, when I first implement the check, using the recursive way, everything works fine
(Example code using recursive way)
let previousBackgroundColor = "";
const getRandomBackgroundColor = (backgroundColorsArray) => {
const getRandomNum = Math.floor(Math.random() * backgroundColorsArray.length);
let randomBackgroundColor = backgroundColorsArray[getRandomNum];
// Prevent show same background color in a row
if (previousBackgroundColor === randomBackgroundColor) {
return getRandomBackgroundColor(backgroundColors);
} else {
previousBackgroundColor = randomBackgroundColor;
return randomBackgroundColor;
}
};
but, when I try to implement the check using other than recursive way(using do…while & while loop), the browser freezes when I keep changing the background color of the body by clicking the button fast, it doesn’t have this kind of problem when using recursive way
(Example code using do…while way)
let previousBackgroundColor = "";
const getRandomBackgroundColor = (backgroundColorsArray) => {
const getRandomNum = Math.floor(Math.random() * backgroundColorsArray.length);
let randomBackgroundColor = '';
// Prevent show same background color in a row
do{
randomBackgroundColor = backgroundColorsArray[getRandomNum];
} while(previousBackgroundColor === randomBackgroundColor)
previousBackgroundColor = randomBackgroundColor;
return randomBackgroundColor;
};
What am I doing wrong?
Other than recursive way to solve the problem, is using do…while or while loop the right approach?
Is recursive the only way to solve this problem?
(Full code that has the problem)
const bodyEl = document.querySelector("body");
const buttonEl = document.querySelector("button");
const backgroundColors = [
"#3D315B",
"#444B6E",
"#9EB7E5",
"#EF959D",
"#CBE896",
"#596F62",
"#F29559",
"#B185A7",
"#BFD1E5",
"#B7C0EE",
"#7067CF",
"#CBF3D2",
];
let previousBackgroundColor = "";
const getRandomBackgroundColor = (backgroundColorsArray) => {
const getRandomNum = Math.floor(Math.random() * backgroundColorsArray.length);
let randomBackgroundColor = "";
do {
randomBackgroundColor = backgroundColorsArray[getRandomNum];
} while (previousBackgroundColor === randomBackgroundColor);
previousBackgroundColor = randomBackgroundColor;
return randomBackgroundColor;
};
const changeBackgroundColor = () => {
bodyEl.style.backgroundColor = getRandomBackgroundColor(backgroundColors);
};
buttonEl.addEventListener("click", changeBackgroundColor);