I wanted to write a simple function which updated a paragraph element <p></p>
every second with new text in a pattern, however I am unsure as to how to go about delaying the method call This is the solution I tried but it doesn't seem to work. If you remove the setTimeout method and replace it with a simple recursive call the function prints out the pattern as it is supposed to but doesn't print it out with a delay which is what I want.
function printPattern(eventSource, width, height, counter){
if(height == 1 && counter >= width) {
return;
}
else{
if(counter >= width){
eventSource.innerHTML += "<br>";
//printPattern(eventSource,width,height-1,0);
setTimeout(printPattern(eventSource,width,height-1,0), 1000)
}
else{
if((counter%2 == 0) ^ (height%2 == 1)){
eventSource.innerHTML += "O";
}
else{
eventSource.innerHTML += "X";
}
//printPattern(eventSource,width,height,counter+1);
setTimeout(printPattern(eventSource,width,height,counter+1), 1000)
}
}
}
function displayPattern(source){
printPattern(source, 4, 4, 0);
}