在 try 块中设置间隔,但如果捕获异常则清除

set Interval in try block but clear if catch an exception

我有一个在 try 块中调用 setInterval 的代码,我在代码末尾清除了间隔,但是如果我的代码捕获并出现异常,setInterval 函数将永远保持 运行。如果我在 try 块中创建的 sqsInterval 在 catch 中不存在,我该如何清除它?

    const createInterval = (message, queueUrl) => {
    let timeout = parseInt(process.env.QUEUE_VISIBILITY_TIMEOUT, 10);
    const interval = setInterval(() => {
      timeout += parseInt(process.env.VISIBILITY_TIMEOUT_INCREMENT, 10);
      if (timeout > 43200) {
        return;
      }
      const params = {
        QueueUrl: queueUrl,
        ReceiptHandle: message.ReceiptHandle,
        VisibilityTimeout: timeout,
      };
      sqs.changeMessageVisibility(params, (err, data) => {
        if (err) logger.error(err, err.stack);
        else logger.info(JSON.stringify(data));
      });
    }, parseInt(process.env.TIMER_INTERVAL, 10));
    return interval;
  };
  try {
    // Starting time for complete clip project
    const queueUrl = process.env.AWS_SQS_VIDEO_CLIPS_QUEUE_URL;
    const sqsInterval = createInterval(message, queueUrl);
    await sleep(30000);
    clearInterval(sqsInterval);
    logger.info(`Finished processing message - [MessageID: ${message.MessageId}], [ReceiptHandle: ${message.ReceiptHandle}] [MD5OfBody]: ${message.MD5OfBody} [noteId=${noteId}]`);
  } catch (error) {
    clearInterval(sqsInterval);

const sqsInterval 的范围在 try{ } 内。用 let

在外面声明
let sqsInterval;
try {
  const queueUrl = process.env.AWS_SQS_VIDEO_CLIPS_QUEUE_URL;
  sqsInterval = createInterval(message, queueUrl);
  await sleep(30000);
  clearInterval(sqsInterval);
  logger.info(`Finished processing message - [MessageID: ${message.MessageId}], [ReceiptHandle: ${message.ReceiptHandle}] [MD5OfBody]: ${message.MD5OfBody} [noteId=${noteId}]`);
} catch (error) {
  clearInterval(sqsInterval);
}