[Solved] How do I stop a function from running early in NodeJS? [duplicate]


I guess you want to stop the execution of the setInterval, for that you could return the setInterval’s result from the function and pass it to a clearInterval to avoid it’s execution.

For this, you might also have to add a check to see if the function has been started or not
But for now, the rewritten script could be something like this

function testFunction(action, process) {
    if (action === "stop") {
        return clearInterval(process);
    } else if (action === "start") {
        return setInterval(() => {
            console.log('hi')
        }, 5000);
    }
}
var process;
process = testFunction("start");
testFunction("stop", process);

Edit
(Since you said that the setInterval case was just an example)
If the code is synchronous then the function will keep executing and you won’t be able to run any code after the function call to stop it. If it is asynchronous, it will depend on the code structure, refer to this for an example.

8

solved How do I stop a function from running early in NodeJS? [duplicate]