setTimeout in websockets

hi,
I am using websockets and am having trouble setting up the set timeout method.
the code from the docs is :

setTimeout(function () {
if (ws.readyState === WebSocket.OPEN) {
ws.send(“Hello WebSocket, I’m a text message.”);
}
else {
console.log(“WebSocket instance wasn’t ready…”);
}
}, 3);
how and where do we use it? also what is a timer handler? the suggestions on set timeout in VSCode say that the function is a timer handler. any help would be much appreciated.
Thanks!!!

About “how and where do we use it”: you use this code whenever you want to check if the connection is opened. Usually the webSocket.onopen event is enough for this, but sometimes it may take too much time. In this case you set a timeout handler. Notice, however, that the interval should be 3000 for 3 seconds.

About “what is a timer handler”: in your code the timer handler is the anonymous function you defined and passed as the argument to the setTimeout() method:

setTimeout(function() { ... }); // <-- the anonymous function here

It’s also worth mentioning that setTimeout() returns the id of the internal timeout object. In your code you are ignoring this value, but you could have stored it in a variable or attribute and used it later to cancel the timeout anytime you want by using the cancelTimeout(id) method.

// somewhere else in your code:
var timeoutId: number = -1;

// your previous code would be:
timeOutId = setTimeout(function() { ... }, 3000);

// to cancel the timeout:
if (this.timeoutId != -1) {
    this.timeoutId = -1;
    cancelTimeout(this.timeoutId);
}

Hope this helps.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.