John Smith
John Smith

Reputation: 107

Javascript setInterval doesn't work

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("&nbsp;&nbsp;");
		}
		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("&nbsp;");
		}
		document.write("**<br>");
	}
}

Upvotes: 0

Views: 554

Answers (3)

Mario
Mario

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

Jean-Pierre Carvalho
Jean-Pierre Carvalho

Reputation: 44

I tested the code on Google Chrome and it worked correctly.

Only had an undefined error in arraySigns.

Image generate tree

Upvotes: 2

Jecoms
Jecoms

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 += "&nbsp;&nbsp;";
    }
    
    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 += "&nbsp;";
    }   
    treeDiv.innerHTML += "**<br>";
  }
}
<div id="theTreeDiv">
  
</div>

Upvotes: 1

Related Questions