Right now, I have an array with three options. I have a function set up so it chooses one option each time, but sometimes it repeats outputs. How can I code it so the same color does no repeat twice in a row?
<!DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8"/>
<title>Tester</title>
<script type="text/javascript">
var colors = ['#ce0e0e', '#079b0c', '#3e3fd6'];
function changeColor(){
var randomColor = colors[Math.floor(Math.random() * colors.length)];
while (myDiv.style.backgroundColor == randomColor)
randomColor = colors[Math.floor(Math.random() * colors.length)];
myDiv.style.backgroundColor = randomColor;
}
</script>
<style>
.divClass {
width:300px;
height:300px;
border: 1px solid black;
border-radius:1000px;
background-color:transparent;
}
</style>
</head>
<body>
<div class=divClass id="myDiv" style="border:6px solid black;">
</div>
<input id=button type=button value="chagne color" onclick='changeColor()'>
</body>
</html>
I tried to use the unique = true but that didn't seem to work.
<script type="text/javascript">
var colors = ['#ce0e0e', '#079b0c', '#3e3fd6'];
var old;
function changeColor(){
var randomColor = colors[Math.floor(Math.random() * colors.length)];
if(old){
if(old !== randomColor){
myDiv.style.backgroundColor = randomColor;
old = randomColor;
} else {
setTimeout(changeColor,300);
}
} else {
myDiv.style.backgroundColor = randomColor;
old = randomColor;
}
}
</script>
They won't repeat now. Old keeps the value of the first/previous click. If you get same value you relaunch function until it changes.
50+ clicks and never same color twice
var color = colors[Math.floor(Math.random() * colors.length)];
function changeColor(){
var newColor = colors[Math.floor(Math.random() * colors.length)];
if(newColor==color){
changeColor();
} else {
color = newColor;
myDiv.style.backgroundColor = color;
}
}
you should use a recursive function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.