0

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);
}

1 Answers1

1

You are passing the result of calling printPattern to setTimeout, instead of passing a function itself. You want:

setTimeout(function() {
  printPattern(eventSource, width, height, counter+1);
}, 1000);
  • 1
    They **are** being passed in as parameters to the call to `printPattern` within the anonymous function given to `setTimeout`. –  Jan 06 '16 at 06:23
  • @torazaburo As the user wishes to update it **every** 1 second, shouldn't he be using setInterval instead ? – Sarath Chandra Jan 06 '16 at 06:31
  • 1
    @SarathChandra Well, there are pros and cons to that. In this case, what he wants to execute next depends on the situation, so I see no problem with using `setTimeout`. –  Jan 06 '16 at 06:32