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。