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

Javascript 仅当代码在3秒内未执行时才执行块,javascript,jquery,angularjs,promise,bluebird,Javascript,Jquery,Angularjs,Promise,Bluebird,我想在我的代码中实现一个承诺,即在块2中运行angular.bootstrap(),前提是3秒已经过去,并且块1中的angular.bootstrap()尚未完成,但只有在以下情况下 我有两段代码: // block 1: Office.initialize = function (reason) { $(document).ready(function () { angular.bootstrap(document, ['myApp']) }) } // bl

我想在我的代码中实现一个承诺,即在
块2
中运行
angular.bootstrap()
,前提是
3秒
已经过去,并且
块1
中的
angular.bootstrap()
尚未完成,但只有在以下情况下

我有两段代码:

// block 1:
Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
    })
}

// block 2:
$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
})
有人知道怎么做吗


编辑1:只是为了澄清,
Office.initialize
可能永远不会执行(即,当应用程序作为加载项加载到Office中时)。在这种情况下,我仍然希望在3秒钟内执行
block 2
angular.bootstrap

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

功能使用:

设置超时:

setTimeout(function, time);`
//function is the function to execute
//time is the duration to wait (in milisecods) before executing the function
clearTimeout(id);`
//id is the id of the setTimeout block to stop from executing
清除超时:

setTimeout(function, time);`
//function is the function to execute
//time is the duration to wait (in milisecods) before executing the function
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'])
}

此解决方案使用下划线JS函数。写一个函数,比如

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

现在,您可以在块1、块2中调用此函数,并在3秒内设置超时。无论哪一个先调用它,都将执行该函数,剩下的调用将是伪调用。

这听起来真像是一个错误。为什么您首先需要两个不同的调用来引导?另外,无需将
angular ready
包装到jQuery ready中,这就是为什么我需要两个不同的调用…@charlietfl我刚刚删除了
angular ready
来简化代码,谢谢你…谢谢你。。。但有可能永远不会执行
Office.initialize
(在Office中加载程序时)。在这种情况下,我仍然希望
angular。块2的
引导在3秒内执行。是的。要解决该问题,可以移动
let wait=setTimeout(myFunction(),3000)语句在
Office前面的一行。在那里的第一块中初始化
,它现在在答案中实现。(请使用
var
而不是
let
)。。。奇怪的是,我刚刚实现了这个,但是似乎
myFunction
总是会立即执行,应该是
setTimeout(myFunction,3000)
myFunction
之后不使用parens。使用parens,它会立即调用函数,然后将返回值从该函数传递给计时器。它不会等待计时器,因为计时器会破坏整个目的
setTimeout()
希望您向其传递函数引用。传递它
myFunction()
立即执行该函数,并传递执行该函数的结果。这是Javascript中的一个常见错误。如果要立即执行函数名,请仅在函数名后使用parens。如果您只是传递一个函数引用以便以后可以执行,那么不要在它之后使用parens。