How to Interrupt setInterval in JavaScript?

1

How do I stop running a setInterval that is running on a module that I do not need anymore? I'm not talking about just getting the setInterval return and executing a clearInterval . That's not it ...

Example:

app.js

// Rota de data e hora para uma página que exibe em tempo real essa informações para o usuário
const dateTimeSystem  = require('./routes/date-time');
// outros códigos
app.use('/datetime' , dateTimeSystem);

date-time.js

// meus códigos...
//...
//..

setInterval(atualizaDataHora, 1000);

function atualizaDataHora() {
    // meus outros códigos...
}

When I access the route to the date time page, this continuous update is correct and can go on indefinitely while I'm on the page. However, when going to any other route / page, I need this function to "UpdateDataTime" no longer run one at a time because I do not need it anymore. I checked in debug mode that it continues to run even after I switch to another page.

How do I stop setInterval in this case?

    
asked by anonymous 09.08.2017 / 22:21

1 answer

1
  

"I'm not talking about just getting the return from setInterval and running a clearInterval."

I think that's exactly it. The "return" of the setInterval is a pointer to be able to call the clearInterval that cancels it. This is the only way to stop the setInterval.

Another way you can use, but do not stop, is to have a flag in the function that returns early if it is not already needed, but to stop even with:

const pointer = setInterval (updateDataTime, 1000);

function atualizaDataHora() {
    // meus outros códigos...

    // e quando já não for mais preciso:
    clearInterval(ponteiro);
}
    
09.08.2017 / 22:24