Reputation: 211
I am trying to teach myself some JavaScript and play around with recursion at the same time. The code I've written below I expect to print "inhale" to the console 10 times with a 5-second delay in between printing. However when I watch the console in Chrome's dev tools, all entries get printed seemingly instantaneously after refreshing the page. Can anyone help me find the error in my implementation? Thank you!
function breathe(type, counter, limit, duration) {
if(counter <= limit) {
setTimeout(console.log(type), duration);
counter++;
return breathe(type, counter, limit, duration);
}
console.log("Finished!");
}
var breathing = breathe("inhale", 1, 10, 5000);
Upvotes: 1
Views: 111
Reputation: 375
var counter = 0;
var duration = 2000
var text = "Inhale";
var limit = 10;
function print(counter, duration, text, limit) {
setTimeout(function(){
console.log(text, counter)
counter++;
if (counter < limit) {
print(counter, duration, text, limit);
}
},duration)
};
print(counter, duration, text, limit);
Try this.
Upvotes: 0
Reputation: 2648
The setTimeout
method expects a function ref. This should work.
function breathe(type, counter, limit, duration) {
if(counter <= limit) {
setTimeout(function(){console.log(type)}, duration);
counter++;
return breathe(type, counter, limit, duration);
}
console.log("Finished!");
}
var breathing = breathe("inhale", 1, 10, 5000);
Upvotes: 2
Reputation: 11
I think this is what you want:
function breathe(type, counter, limit, duration) {
if(counter <= limit) {
setTimeout(function(){
console.log(type);
counter++;
return breathe(type, counter, limit, duration);
}, duration);
}
console.log("Finished!");
}
var breathing = breathe("inhale", 1, 10, 5000);
Upvotes: 0
Reputation: 84912
setTimeout(console.log(type), duration);
This is immediately executing console.log(type)
, and then passing the result into setTimeout. The result of console.log is undefined
, so nothing happens when the timeout goes off.
Instead, you want to do this:
setTimeout(function () {
console.log(type);
}, duration);
Upvotes: 1
Reputation: 25383
This is because you are executing your console
statement immediately (since you are executing console.log
via the ()
), rather than passing in a function reference to setTimeout
:
setTimeout(console.log(type), duration);
Try this instead:
setTimeout(function() {
console.log(type)
}, duration);
Another form you could use (just to hammer-home the concept of passing a function reference) is this:
function callMeAfterDelay() {
console.log(type);
}
setTimeout(callMeAfterDelay, duration);
Upvotes: 1