Is there a way to automatically stop changing the background color with random colors after a few seconds when clicking on a start button? I attempted using setTimeout() but my limited understanding of JavaScript has hindered me from finding a solution.
I would greatly appreciate it if someone could assist me in resolving this issue.
function setColor(randomColor){
var body = document.body;
body.style.backgroundColor=randomColor;
var span = document.querySelector(".color");
span.innerText = "\t"+randomColor;
}
function changeColor(){
var randomColor = "#"+Math.floor(Math.random()*16777215).toString(16);
setColor(randomColor);
}
const stopDisco = () => {
var btn = document.querySelector("button");
setColor("#ffffff");
}
function startDisco(){
var btn = document.querySelector("button");
changeColor();
let interval = setInterval(changeColor, 50);
var stopBtn = document.querySelector(".stop")
stopBtn.addEventListener('click', function () {
clearInterval(interval);
stopDisco();
})
}
<body>
<div>
<button class="on" onclick="startDisco()">Start Disco</button>
<button class="stop">Stop Disco</button>
<p>Hex Color:<span class ="color">#FFFFFF</span></p>
</div>
</body>