rafaelgara
rafaelgara

Reputation: 63

clearInterval of a external function not working - Node.JS

I have a setInterval function that's been called in another function, and I need to stop it when the proccess is done. I tried to set this setInterval function as a variable and call clearInterval, but the interval keeps running

 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);
  }
};

I know that if i create a var test = setInterval(() => {console.log('blabla')}, 500) and call clearInterval(test) it works, but i don't know how can i do this calling a function

Upvotes: 1

Views: 305

Answers (1)

Bogdan R.
Bogdan R.

Reputation: 49

I think that you have to return from createInterval function the intervalId and after that it should work.

Can you check what value has your intervalId right now, with your current implementation?

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

"The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to clearInterval() to cancel the interval."

Upvotes: 1

Related Questions