'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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mattias Martens