Aleksander Sadaj
Aleksander Sadaj

Reputation: 194

How does one use JS clearTimeout with parameters?

I wanted to create a very simple function that would simulate window blind's movement. It is run on a server that will receive a request with direction parameter that says whether the blind should go UP, DOWN or it should STOP.

The simulation is supposed to work like this: request comes in with the direction parameter, server responds that the blind is MOVING. The movement, no matter the direction, will last 10 secs as it can be seen in the setTimeout function. The point is that if server receives a request with direction === STOP then the server should call clearTimeout to "stop" the blind's movement and return a different blind state, saying that the blind is PARTLY_CLOSED.

So far it works this way, that if I send a request with some direction, server responds with MOVING as it should. When I call clearTimeout during the "movement" it actually starts a second setTimeout function.

My question is: how do I make the code right and how do I parametrize the setTimeout function?

Here is the code:

let blindState = "OPENED";
const blindMovementFunction = (direction) => setTimeout((direction) => {
    console.log("### direction", direction);
    if (direction === "UP") {
        blindState = "OPENED"
    } else if (direction === "DOWN") {
        blindState = "CLOSED";
    }
}, 10000);

Usage inside the endpoint:

if (req.query.direction === "STOP") {
            console.log("### blindMovementFunction", blindMovementFunction);
            clearTimeout(blindMovementFunction);
            blindState = "PARTLY_CLOSED";
            res.send(blindState);
        } else {
            blindState = "MOVING";
            res.send(blindState);

            blindMovementFunction(req.query.direction);
        }

Upvotes: 0

Views: 231

Answers (1)

Satpal
Satpal

Reputation: 133403

You are passing the function reference to clearTimeout, it needs timeoutID returned by setTimeout()

Define in global scope

var timeoutID;

Persist the timeout-id return by setTimeout() method

timeoutID = blindMovementFunction(req.query.direction)

and

clearTimeout(timeoutID);

Upvotes: 3

Related Questions