如何在上次调用函数后的5秒间隔内执行函数?

时间:2018-08-02 23:14:51

标签: angularjs

我的控制器中有一个函数(testFunction),它在随机的时间间隔内被随机调用(由callFunction调用)。因此,例如,callFunction可以调用testFunction 10次;等待30秒;然后调用testFunction 20次;等待24小时,然后调用testFunction 2次,等等。。。我想在该函数调用的最后一个实例之后5秒钟执行另一个函数。例如:

vm.testFunction = () => {
   console.log("a");
   if(some conditional statement that determines that it's been five seconds since this function was last called)
    { 
       console.log("b");
       callTestFunction2();
    }
}

问题输入:

callFunction() calls testFunction 2 times; waits 30 seconds; calls 
testFunction 3 times; waits 2 seconds; calls testFunction 10 times:
The answer should be 
aabaaaaaaaaaaaaab

1 个答案:

答案 0 :(得分:0)

听起来您想使用$interval$timeout

$timeout docs$interval docs

如果您想在5秒钟后致电callTestFunction2(),看起来像这样

vm.testFunction = () => {
   console.log("a");
   $timeout(function() { 
       console.log("b");
       callTestFunction2();
    }, 5000); // Delay is in milliseconds 5 secs = 5000
}