【问题标题】:clearInterval of a external function not working - Node.JS外部函数的 clearInterval 不起作用 - Node.JS
【发布时间】:2022-01-13 11:28:03
【问题描述】:

我有一个在另一个函数中调用的 setInterval 函数,我需要在进程完成后停止它。我试图将这个setInterval函数设置为变量并调用clearInterval,但间隔一直在运行

 const createInterval = (visibilityTimeout, startDateTime, message) => {
  setInterval(() => {
    const currentDateTime = moment().valueOf();
    const timeDifference = (visibilityTimeout * 1000) - (currentDateTime - startDateTime);
    if (timeDifference >= 600000) {
      return;
    }
    if (timeDifference < 494983) {
      const params = {
        QueueUrl: 'http://localhost:4566/000000000000/test-queue2',
        ReceiptHandle: message.ReceiptHandle,
        VisibilityTimeout: visibilityTimeout,
      };
      sqs.changeMessageVisibility(params, (err, data) => {
        if (err) logger.error(err, err.stack);
        else logger.info(data);
      });
      // eslint-disable-next-line no-param-reassign
      visibilityTimeout += 300;
    }
  }, 5000);
};

module.exports = async (message) => {
  const startDateTime = moment().valueOf();
  const {
    noteId,
  } = JSON.parse(message.Body);

  logger.info(`Processing message [noteId=${noteId}]`);
  try {
    const note = await TestSessionNote.findById(noteId);
    const testSession = await TestSession.findById(note.test_session_id);
    logger.info(`Downloading video [key=${testSession.video_key}]`);

    const isProcessing = true;
    const interval = createInterval(500, startDateTime, message, isProcessing);
    await sleep(20000);
    clearInterval(interval);
    logger.info(`Finished processing message [noteId=${noteId}]`);
  } catch (ex) {
    await TestSessionNote.update(noteId, { status: 'transcribe_error' });
    logger.error(`Error processing message [noteId=${noteId}]`, ex);
  }
};

我知道如果我创建一个 var test = setInterval(() => {console.log('blabla')}, 500) 并调用 clearInterval(test) 它可以工作,但我不知道我该怎么做这样做调用一个函数

【问题讨论】:

  • 你没有从createInterval返回任何东西。使用return setInterval(...)

标签: node.js setinterval clearinterval


【解决方案1】:

我认为您必须从 createInterval 函数返回 intervalId,然后它应该可以工作。

你能用你当前的实现检查你的 intervalId 现在有什么值吗?

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

"返回的 intervalID 是一个数字的非零值,用于标识调用 setInterval() 创建的计时器;该值可以传递给 clearInterval() 以取消间隔。"

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多