Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
setInterval() still triggering after clearInterval() in NodeJS

I have the following code setting and clearing an interval inside a NodeJS script.

Starting interval works fine, but when trying to clear it, the stopping interval console will trigger, but the interval will continue firing every minute.

app.get("/api", async (req, res) => {

    active = req.query.active;
    
    let interval = null;

    if (active == "true") {

        console.log("starting interval");

        interval = setInterval(async function() {
            try {
                const Posts = await getPosts();
                const Comments = await getComments();
                sendPosts().then(() => sendComments());

            } catch (e) {
                throw e;
            };
        }, 60000);

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: true});

    } else {

        console.log("stopping interval");

        clearInterval(interval);
        interval = null;

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: false});
    }
    
});

What am I missing?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your interval variable is declared inside the route handler. Every time the route is called, a new interval variable is created. Reassigning that variable inside one invocation of the route does not change its value during other invocations of the route. You need:

let interval = null;
app.get("/api", async (req, res) => {
    // ...

You should also catch errors properly - your current approach will result in unhandled rejections here:

    interval = setInterval(async function() {
        try {
            const Posts = await getPosts();
            const Comments = await getComments();
            sendPosts().then(() => sendComments());

        } catch (e) {
            throw e;
        };
    }, 60000);

Only throw if there's something that can handle it up the call stack - if not, you should do whatever you reasonably can with the error at that point and stop without throwing.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to move "let interval" outside of the call to app.get().

Right now the variable is declared inside the closure of the function which means it gets initialized every time a request comes in.

If it's outside the function, the variable becomes part of the global scope and its value will be remembered between requests.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda