简体   繁体   English

如何在一个间隔内停止多次调用一个函数?

[英]How can I stop multiple calls to a function inside an interval?

How could I ensure that one one call of a function in an interval can run at once? 如何确保间隔内一次调用一个函数一次?

My code looks like this: 我的代码如下所示:

var promisePutTestQuestion;

   onEnter: ['$interval', 'questionService',
             ($interval, qus: IQuestionService) => {
      promisePutTestQuestion = $interval(() => {
         qus.putTestQuestionResponses();
      }, 5 * 1000);
   }],
   onExit: ['$interval',
            ($interval) => {
             $interval.cancel(promisePutTestQuestion);             
   }],

The problem I am having is if the putTestQuestionResponse (which returns a promise) is slow then I have multiple putTestQuestionResponse function calls one after the other. 我遇到的问题是,如果putTestQuestionResponse(返回承诺)速度很慢,则我有多个putTestQuestionResponse函数一个接一个地调用。

Would appreciate if anyone has any ideas on this. 如果有人对此有任何想法,将不胜感激。 Thanks 谢谢

In javascript it's safe to use state variable for this purpose. 在javascript中,为此目的使用状态变量是安全的。 Whenever qus.putTestQuestionResponses operation takes a lot of time next call will be skipped. 每当qus.putTestQuestionResponses操作花费大量时间时,下一个调用将被跳过。 So just maintain right state of processing variable, and if it's true quit the interval callback without running task again. 因此,只需保持处理变量的正确状态即可,如果正确,则退出间隔回调,而无需再次运行任务。

var promisePutTestQuestion;
let processing = false;

onEnter: ['$interval', 'questionService',
         ($interval, qus: IQuestionService) => {
  promisePutTestQuestion = $interval(() => {
     if (processing)
         return;
     processing = true;
     qus.putTestQuestionResponses()
     .then(() => processing = false)
  }, 5 * 1000);
}],
onExit: ['$interval', ($interval) => {
        $interval.cancel(promisePutTestQuestion);
}]

Not sure what promise framework you're using, but () => processing = false should be either in finally() for $q I guess, and in the then that should be after catch to ensure it is executed in any case. 不确定您使用的是什么promise框架,但是我猜$ q应该在finally()使用() => processing = falsethencatch中确保在任何情况下都执行该框架。 So one of these: 因此,其中之一:

qus.putTestQuestionResponses().finally(() => processing = false)

or 要么

qus.putTestQuestionResponses().catch(...).then(() => processing = false)`

or even 甚至

qus.putTestQuestionResponses().then(() => processing = false).catch(() => processing = false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM