0

If ws.send throws an exception for the code below, I want to ensure that I stop recursively sending and that the client thread ends.

function newAlarm(ws)
{
    ws.send(alarm);
}

function loop(f,t)
{
    setTimeout(() => loop(f,t), t);
    f();
}

loop(() => newAlarm(ws),10000);

I understand that to catch the error for ws.send, I do the following: ws.send(alarm, err => {if(!err){...}}) But I can't figure out how to do this for setTimeout.

1 Answer 1

2

Try adding a variable to hold your timer, then clearing it when you want it to stop.

function newAlarm(ws)
{
        ws.send(alarm);
}

function loop(f,t)
{
    var timer = setTimeout(() => loop(f,t), t);
    try{
        f();
    }
    catch{
        clearTimeout(timer);
    }
}

loop(() => newAlarm(ws),10000);
Sign up to request clarification or add additional context in comments.

3 Comments

But newAlarm is no longer a pure function.
Can you put a try-catch around f() in your loop and call clearTimeout(timer) in the catch? It worked for a toy example I tried. I updated the code in my answer.
This works and I prefer it to your first answer, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.