bert
bert

Reputation: 13

Recursive function to print numbers in JavaScript

I'm trying to make a recursive function to print 1 to 10 in JavaScript, my current code is:

function rec10(x)
 {

       if (x < 10)
       {

       $('#text').val(x+1);
       x = x+1;
       rec10(x);

       }



 }

The problem is, everytime I activate this function, the text box only shows "10" directly, i want the code to move from 0 to 1, to 2... until 10. Showing each one of them in the text box. I tried to use setInterval and setTimeout but I didn't figure it out how to work with that. Thank you very much

Upvotes: 1

Views: 1868

Answers (4)

jcera
jcera

Reputation: 345

Did you resort to setInterval/setTimeout only because you can't make a working recursive function?
If that's the case, how about this recursive function below without using setInterval/setTimeout:

function rec10(x) {
    if (x <= 10) {
        if (x <= 0) x = 1;

        //append?
        $('#text').val(x);

        rec10(x + 1);
    }
}

rec10(1);  

But the problem with the code above is it will happen so fast you won't notice the printing of numbers 1 up to 9. If you want to see the those numbers then I suggest you just append the value to your placeholder $('#text').
But if you really wanna see the numbers being printed and then being replaced by the next number, then you can refer to the answers posted by other users which uses setInterval/setTimeout.

Upvotes: -1

Abruzzi
Abruzzi

Reputation: 495

With setInterval you can using code below:

function rec10(x) {
    var interval = setInterval(function() {
        if (x >= 10) clearInterval(interval);
        $('#text').val(x++);
    }, 1000);
 }

Upvotes: 1

Evert
Evert

Reputation: 99599

instead of:

rec10(x);

call

setTimeout(function() { rec10(x); }, 1000);

Upvotes: 4

gdoron
gdoron

Reputation: 150263

JavaScript is single threaded, which means while your code runs, the changes you make to the DOM won't be seen on the browser until your code finish.

You need to give control to the browser for couple of seconds, it can be done with setTimeout:

function rec10(x){

       if (x < 10){
           $('#text').val(++x);

       setTimeout(function(){
           rec10(x);               
       },20);

       }
 }

Upvotes: 0

Related Questions