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?
CodePudding user response:
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);
CodePudding user response:
you can also simply return the message which do you want:
wait(100, 30);
function wait(time, limit) {
console.log("value >> " limit);
if (limit < 0) return console.log("hi");
setTimeout(function () {
wait(time, --limit);
}, time);
}
CodePudding user response:
In addition to Nina's approach and also for use cases where a callback can not be implemented as easily as demonstrated with Nina's example code, one might use an abstraction for it, which for JavaScript is Promise
s.
Here, instead of 30 times delaying for 100 milliseconds until logging, one would implement wait
as promise which resolves after 3 seconds with the additional logging provided as thenable ...
const wait = new Promise(resolve => setTimeout(resolve, 3000));
wait.then(() => console.log('hi'));
console.log({ wait: String(wait) });
.as-console-wrapper { min-height: 100%!important; top: 0; }