仅在3秒内未执行代码时执行块

时间:2017-07-09 01:45:52

标签: javascript jquery angularjs promise bluebird

我希望在我的代码中实现一个承诺,如果angular.bootstrap()已经过block 2并且3 seconds中的angular.bootstrap()尚未完成,则block 1中会运行// block 1: Office.initialize = function (reason) { $(document).ready(function () { angular.bootstrap(document, ['myApp']) }) } // block 2: $(document).ready(function () { angular.bootstrap(document, ['myApp']) }) ,但仅限于。

我有两个代码块:

Office.initialize

有谁知道怎么做?

编辑1:只是为了澄清angular.bootstrap永远不会被执行(即,当应用程序作为加载项加载到Office中时)。在这种情况下,我仍然希望在3秒内执行block 2 Dim ListA As List (Of SomeClass) Dim ListB As List (Of SomeClass) '... 'Assuming both lists are initialized and populated Dim ListC As List (Of SomeClass) = (From itemA In ListA Join itemB In ListB On itemA.A Equals itemB.A Select itemA).ToList()

2 个答案:

答案 0 :(得分:1)

您可以在JavaScript中使用setTimeout()clearTimeout()函数。

功能用法:

setTimeout:

setTimeout(function, time);`
//function is the function to execute
//time is the duration to wait (in milisecods) before executing the function

clearTimeout:

clearTimeout(id);`
//id is the id of the setTimeout block to stop from executing

这是您在代码中实现这些功能的方法:

// block 1:
var wait = setTimeout(myFunction, 3000);
Office.initialize = function (reason) {
  $(document).ready(function () {
      angular.element(document).ready(function () {
          angular.bootstrap(document, ['myApp'])
          clearTimeout(wait);
      })
  })
}

// block 2:
function myFunction() {
  angular.element(document).ready(function () {
      angular.bootstrap(document, ['myApp'])
}

答案 1 :(得分:0)

此解决方案使用underscorejs once函数。写一个像

这样的函数
var bootstrapInit = _.once(function(){
angular.bootstrap(document, ['myApp']);
});

现在,您可以在块1,块2和setTimeout中调用此函数3秒。无论哪个首先调用它都将执行该函数,剩下的调用将是虚拟调用。