Mark C.
Mark C.

Reputation: 6450

Change innerHTML color randomly in loop

I am trying to run a loop that will continuously change the color by randomly generating hex codes. I tried to search on here but couldn't find anything doing this.

I can't figure out how to get a loop to run and change the color continuously (until the end of a loop). I am new to JavaScript.

Here's my JSFiddle.

HTML

<body>
<div id="outer">
    <div id="test">Generate colors.</div>
</div>
</body>

JS

for ( i = 0; i < 20000; i++ ) {
    var t = document.getElementById('test');
    var z = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    t.style.color = z
}

Upvotes: 2

Views: 1487

Answers (4)

flyandi
flyandi

Reputation: 1939

You don't loop - you interval:

var target= document.getElementById('test'),
colorChange = function() {
    target.style.color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
};

// run interval
var d = setInterval(function() {

     colorChange();
}, 500);

// clear after 5s

setTimeout(function() {
    clearInterval(d);
}, 5000);

Working JSFiddle: http://jsfiddle.net/046q6ohf/

Upvotes: 0

Charles
Charles

Reputation: 437

I know it's already been answered, but mine includes the cleartimeout to set a timer.

var myVar = setInterval(function(){changeColor()}, 1000);
setTimeout(function(){clearInterval(myVar)}, 5000);

The second argument in the call to setTimeout could serve as your timer, so that the animation stops afterwards, in this case, it's set to 5 seconds.

function changeColor() {
    var t = document.getElementById('test');
    var z = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    t.style.color = z;
    console.log(z);
}

Result: Result

Upvotes: 1

LcSalazar
LcSalazar

Reputation: 16841

You were right with the commented setInterval you have on fiddle. It will make the colors change periodically (according to the milliseconds defined).

But you have to remove the for loop, because it will run instantly and you won't even see the changes... You'll have to manage your own variable counter, and clear the interval after it:

http://jsfiddle.net/kkfnjpsh/5/

var i = 0;
var runner = setInterval(function(){
    if(i < 20000) {
        var t = document.getElementById('test');
        var z = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        t.style.color = z;
        i++;
    }
    else {
        clearInterval(runner);
    }
}, 3000);

Upvotes: 1

Guffa
Guffa

Reputation: 700392

You can't change colors in a loop, the color of the element won't change until you exit the code and return control to the browser.

You can use an interval to run code and return the control to the browser each time:

window.setInterval(function(){
  var t = document.getElementById('test');
  var z = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
  t.style.color = z
}, 100);

Demo: http://jsfiddle.net/et3qtr3t/

Upvotes: 1

Related Questions