How do I output this recursive function correctly to a web browser?

Joined
Sep 12, 2022
Messages
39
Reaction score
0
I believe, the code is correct, the issue is with the output to a web browser. What's the fix?

JavaScript:
function countdown(n){
    if (n < 1) {
      return document.getElementById("recursivep").innerHTML = [];
    } else {
       let firstarr = countdown(n - 1);
       firstarr.unshift(n);
       return document.getElementById("recursivep").innerHTML = firstarr;
    }
}

HTML:
<!DOCTYPE html>
<html>
    <head>
        <script async src="Recursive function.js"></script>
    </head>
    <body>
        <main>
            <div>
                Recursive function
                <button onclick="countdown()">click me</button>
                <p id="recursivep"></p>
            </div>
        </main>
    </body>
</html>
 
Joined
Jul 3, 2022
Messages
93
Reaction score
23
JavaScript:
function countdown(n){
    const p = document.getElementById('recursivep');
    if (n < 1) {
      p.innerHTML = 'Boom!';
    } else {
       p.innerHTML = n;
       n--;
       setTimeout(countdown, 1000, n);
    }
}

HTML:
<button onclick="countdown(10)">click me</button>
 
Joined
Sep 12, 2022
Messages
39
Reaction score
0
JavaScript:
function countdown(n){
    const p = document.getElementById('recursivep');
    if (n < 1) {
      p.innerHTML = 'Boom!';
    } else {
       p.innerHTML = n;
       n--;
       setTimeout(countdown, 1000, n);
    }
}

HTML:
<button onclick="countdown(10)">click me</button>
It works. So far my experience with recursive function output has only been via setTimeOut()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top