如果功能,我怎么能运行其余的代码

时间:2018-03-03 13:42:56

标签: javascript jquery

正如标题所说,我怎样才能运行其余的代码(在主函数之下),只有当某些条件完成时?例如:

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");

3 个答案:

答案 0 :(得分:2)

你应该使用promise来做..然后你的代码会是这样的

  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");
})

答案 1 :(得分:0)

您可以将console.log包装在函数中,然后在满足条件后调用该函数。

在下面的解决方案中,console.log将在10秒后触发。



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");
}




答案 2 :(得分:0)

您将foosetInterval混淆。对foo的调用实际上是在控制台日志之前“完成”。我认为你的意思是“它应该在符合setInterval中的函数条件后显示。”

在这种情况下,有几种方法可以做到这一点,最简单的可能只是包装你感兴趣的功能,正如void在他的回答中所表明的那样。另一种方法可能是使用promises或其他类型的异步流。

相关问题