简体   繁体   中英

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

instead of:

rec10(x);

call

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

With setInterval you can using code below:

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

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

       }
 }

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM