Search code examples
javascriptjqueryangularjspromisebluebird

Execute a block only when a code has not been executed in 3 seconds


I want to implement a promise in my code to run angular.bootstrap() in block 2 if 3 seconds has passed and angular.bootstrap() in block 1 has not been done, but only if.

I have two blocks of code:

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

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

Does anyone know how to do this?

Edit 1: Just to clarify that it is possible that Office.initialize is never executed (ie, when the app is loaded in Office as an add-in). In this case, I still want to execute angular.bootstrap of block 2 in 3 seconds.


Solution

  • You can use the setTimeout() and clearTimeout() functions in JavaScript.

    Function usage:

    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
    

    This is how you would implement the functions into your code:

    // 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'])
    }