简体   繁体   中英

Calling a javascript function infinitly on click of a button?

Okay so this is a bit of a weird request. So I've programmed tiles that generate using JavaScript (with the help of people here on stack overflow) now I would like to make it so that on the click of a button my changecolors function is called a set number of times so that the colors of the tiles randomly change before your eyes. I've got a button that every time you click it the colors change, but how can I make it so on that click they continuously change? I've tried using the JavaScript function set Interval(function, time) and couldn't seem to get it to work. Just in case, I will also inform you that I am putting a button in that will also stop the random color changes.. Here's the code. Any help would be great!!

<!doctype html>
<html>
<style>
.cell {
  width: 100px;
  height: 100px;
  display: inline-block;
  margin: 1px;
  padding:4px;
}
button{
float:left;
padding:4px;
}
</style>


<title></title>
<head><script type="text/javascript">
function generateGrid(){
  for (i = 0; i < 5; i++) {
    for (b = 0; b < 5; b++) { 
      div = document.createElement("div");
      div.id = "box" + i +""+ b;
      div.className = "cell";
      document.body.appendChild(div);
    }
    document.body.appendChild(document.createElement("br"));
  }
}
function changeColors(){
for(i =0;i < 5; i++){
    for (b=0;b<5;b++){
        var holder=document.createElement("div");
        holder=document.getElementById("box" + i +""+ b);
        holder.style.backgroundColor = getRandomColor();

    }
}

}
function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
</script>
</head>


<body>
<script>

generateGrid();

changeColors();


</script>
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="window.setInterval(changeColors(),2000);">Click me to start cycle</button>
</body>





</html>

Your setTimeoutFunction was not sintatically correct

 var stop = false; function generateGrid(){ for (i = 0; i < 5; i++) { for (b = 0; b < 5; b++) { div = document.createElement("div"); div.id = "box" + i +""+ b; div.className = "cell"; document.body.appendChild(div); } document.body.appendChild(document.createElement("br")); } } function changeColors(){ for(i =0;i < 5; i++){ for (b=0;b<5;b++){ var holder=document.createElement("div"); holder=document.getElementById("box" + i +""+ b); holder.style.backgroundColor = getRandomColor(); } } } function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; } document.addEventListener("DOMContentLoaded", function(event) { generateGrid(); changeColors(); });
 .cell { width: 100px; height: 100px; display: inline-block; margin: 1px; padding:4px; } button{ float:left; padding:4px; }
 <!doctype html> <html> <title></title> <body> <button onclick="changeColors();">Click me to change colors</button> <button onclick="window.setInterval(function(){changeColors();},2000);">Click me to start cycle</button> </body> </html>

Edited to work without jQuery

Your changeColors() should have been changeColors for window.setInterval .

I cleaned up your code and added the stop/start buttons. By creating an array of elements, it saves the changeColors function having to locate each element every iteration. Lastly I changed your generateGrid function to accept a width and height. A bit overkill but I got carried away :)

HTML

<button onclick="changeColors();">Click me to change colors</button>
<button onclick="startCycle();">Start cycle</button>
<button onclick="stopCycle();">Stop cycle</button>
<br>
<br>

JavaScript

var elements = [];
function generateGrid(width, height) {
    for (var y = 0; y < height; y++) {
        for (var x = 0; x < width; x++) {
            var div = document.createElement("div");
            div.id = "box" + y + "" + x;
            div.className = "cell";
            document.body.appendChild(div);
            elements.push(div);
        }
        document.body.appendChild(document.createElement("br"));
    }
}

function changeColors() {
    for (e in elements) {
        elements[e].style.backgroundColor = getRandomColor();
    }
}

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

var interval = null;
function startCycle() {
    if (interval) return;
    interval = window.setInterval(changeColors, 500);
}

function stopCycle() {
    clearInterval(interval);
    interval = null;
}

generateGrid(3, 5);
changeColors();

Demo

Simple Just added one function on Click of button try this:

 <style> .cell { width: 100px; height: 100px; display: inline-block; margin: 1px; padding:4px; } button{ float:left; padding:4px; } </style> <title></title> <head><script type="text/javascript"> function generateGrid(){ for (i = 0; i < 5; i++) { for (b = 0; b < 5; b++) { div = document.createElement("div"); div.id = "box" + i +""+ b; div.className = "cell"; document.body.appendChild(div); } document.body.appendChild(document.createElement("br")); } } function changeColors(){ for(i =0;i < 5; i++){ for (b=0;b<5;b++){ // var holder=document.createElement("div"); var holder=document.getElementById("box" + i +""+ b); holder.style.backgroundColor = getRandomColor(); } } } function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; } </script> </head> <body> <script> generateGrid(); changeColors(); function animate1() { setInterval(function(){ changeColors(); },5000); } </script> <button onclick="changeColors();">Click me to change colors</button> <button onclick="animate1();">Click me to start cycle</button> </body>

Note: setTimeout function gets called only once after your set duration where setTimeout gets called indefinite unless you use clearInterval() to Stop it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM