Reputation: 107
I have this code that has to be a tree with random signs. I put setInterval to change the signs every second, but nothing happens and I don't get even any error. Someone please tell me where I made a mistake, or more :).
window.onload = intervalSetup;
function intervalSetup() {
'use strict';
setInterval(function() {
theTree();
}, 1000);
}
function theTree() {
'use strict';
var x = 8;
for (var i=0; i<x; i++) {
for (var j=x-1; j>i; j--) {
document.write(" ");
}
for (var k=0; k<=(i*2); k++) {
document.write(arraySigns[Math.floor(Math.random() * arraySigns.length)]);
}
document.write("<br>")
}
for (var i=0; i<2; i++) {
for (var j=0; j<(x*2)-3; j++) {
document.write(" ");
}
document.write("**<br>");
}
}
Upvotes: 0
Views: 554
Reputation: 8300
The script has removed itself by writing to the document. That was the reason, the function was never called twice.
Funny bug, I think. :-)
Upvotes: 2
Reputation: 44
I tested the code on Google Chrome and it worked correctly.
Only had an undefined
error in arraySigns
.
Upvotes: 2
Reputation: 2838
The first problem was an undefined array, which was fixed in an edit.
The remaining problem was that the trees were being written to the page endlessly and it was hard to see the symbols changing.
By generating the tree in a container div which is cleared before each new tree, you can easily see that the symbols were properly random each time.
The snippet has a working example that functions by adding to the innerHTML of the treeDiv. (I took out the document fragment for readability)
'use strict';
window.onload = intervalSetup;
var arraySigns;
var treeDiv;
function intervalSetup() {
arraySigns = ["*", "^", "&", "#"];
treeDiv = document.getElementById("theTreeDiv");
setInterval(theTree, 1000);
}
function theTree() {
treeDiv.innerHTML = '';
var x = 8;
for (var i=0; i<x; i++) {
for (var j=x-1; j>i; j--) {
treeDiv.innerHTML += " ";
}
for (var k=0; k<=(i*2); k++) {
treeDiv.innerHTML += arraySigns[Math.floor(Math.random() * arraySigns.length)];
}
treeDiv.innerHTML += "<br>";
}
for (var i=0; i<2; i++) {
for (var j=0; j<(x*2)-3; j++) {
treeDiv.innerHTML += " ";
}
treeDiv.innerHTML += "**<br>";
}
}
<div id="theTreeDiv">
</div>
Upvotes: 1