Reputation: 177
As the title says how can I run rest of code (which is below the main function), only when some condition is done? For example:
function foo() {
count = 0;
var interval = setInterval(function() {
count++;
if (count == 10) {
clearInterval(interval);
console.log('Done');
}
}, 1000);
}
foo();
console.log("It should display after Foo() is done");
Upvotes: 0
Views: 39
Reputation: 237
you should use promise
for this.. Then Your code will be something like this
function foo() {
return new Promise(function(resolve , reject){
count = 0;
var interval = setInterval(function() {
count++;
if (count == 10) {
clearInterval(interval);
console.log('Done');
resolve();
}
}, 1000);
})
}
foo().then(function(){
console.log("It will be displayed after Foo() is done");
})
Upvotes: 2
Reputation: 23955
You are confusing foo
with setInterval
. The call to foo
is actually "done" before the console log. What I think you might mean is "it should display after the condition in the function in setInterval
is met."
In that case, there are several ways to do it, the simplest probably being just wrapping the functionality you're interested in, as void demonstrates in his answer. Another way might be to use promises or another kind of async flow.
Upvotes: 0
Reputation: 36703
You can wrap the console.log
in a function and then can call the function once the condition is met.
In the solution below, console.log
will get triggered after 10 secs.
function foo() {
count = 0;
var interval = setInterval(function() {
count++;
if (count == 10) {
clearInterval(interval);
console.log('Done');
execAfterFoo(); // Will execute after the condition is met
}
}, 1000);
}
foo();
function execAfterFoo() {
console.log("It should display after Foo() is done");
}
Upvotes: 0