Search code examples
javascriptrecursionsettimeout

How to wait for the recursive loop to finish and display the message?


I'm running a recursive function with setTimeout, what I've noticed is that javascript goes straight through the wait() function and doesn't wait for it to finish. It goes right through and leaves the wait() method working by itself.

wait(100, 30)

function wait(time, limit) {
    console.log('value >> ' + limit)
    if (limit < 0) return 'success'
    setTimeout(function () {
        wait(time, --limit)
    }, time)
}

console.log('hi')

Note that my "hi' message is at the top when running the script, because it went straight through without waiting for the recursive loop. My "hi" message should be at the end.

Can anyone help me leave the hi message at the end after running all the loop?


Solution

  • You could handover a function which is called at the end of waiting.

    function wait(time, limit, fn) {
        console.log('value >> ' + limit)
        if (limit < 0) return fn();
        setTimeout(function () {
            wait(time, --limit, fn);
        }, time)
    }
    
    function sayHi() { console.log('hi'); }
    
    wait(100, 30, sayHi);