I have a code that calls a setInterval in the try block and I clear the interval in the end of the code, but if my code catch and exception, the setInterval function keeps running forever. How can I clear this if the sqsInterval that I created in the try block doesn't exist in the 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);
CodePudding user response:
const sqsInterval
is scoped inside try{ }
. Declare it outside with 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);
}