Using an AngularJS timeout

后端 未结 1 1239
天命终不由人
天命终不由人 2021-01-03 05:02

I\'m new to AngularJS. I\'m currently looking at the $timeout service. I understand that it\'s like a wrapper for the setTimeout function. The documentation says that it pro

相关标签:
1条回答
  • 2021-01-03 05:39

    $timeout is most awesome indeed.

    Exception handling

    $timeout returns a promise which can have an error state. For example

     var timePromise = $timeout(function(){ 
        throw new Error('I messed up');
     }, 10000);
    
     timePromise.catch(function(err){
        // do something with the error
     });
    

    read all about promises here.


    Cancel

    Canceling a $timeout is easy. Instead of using clearTimeout you pass the promise back.

     var timePromise = $timeout(function(){
         // do thing
     }, 23432);
    
     // wait I didn't mean it!
     $timeout.cancel(timePromise);
    

    Flush

    Flush is most useful for unit testing, ultimately it fires any outstanding callbacks.

    $timeout(function(){
       console.log('$timeout flush');
    }, 222);
    
    $timeout(function(){
       console.log('rocks my face');
    }, 234232);
    
    $timeout.flush(); // both console logs will fire right away!
    

    or this file:

    var itsDone = false;
    $timeout(function(){
       itsDone = true;
    }, 5000);
    

    with this test:

    // old no flush way (async)
    it('should be done', function(done){
       expect(isDone).to.be.false;
       setTimeout(function(){
          expect(isDone).to.be.true;
          done();
       }, 5001);
    });
    
    // now with flush
    it('should be done', function(){
       expect(isDone).to.be.false;
       $timeout.flush();
       expect(isDone).to.be.true;
    });
    
    0 讨论(0)
提交回复
热议问题