1

I have two questions regarding the following socket.io code snippet:

const withTimeout = (onSuccess, onTimeout, timeout) => {
  let called = false;

  const timer = setTimeout(() => {
    if (called) return;
    called = true;
    onTimeout();
  }, timeout);

  return (...args) => {
    if (called) return;
    called = true;
    clearTimeout(timer);
    onSuccess.apply(this, args);
  };
}

socket.emit("hello", 1, 2, withTimeout(() => {
  console.log("success!");
}, () => {
  console.log("timeout!");
}, 1000));

Question 1: withTimeout returns a callback that we (the server) emit to the client. If the client does not call the emitted callback before the timer runs out, we should get "timeout" printed on our (server) console, right? Eventually, the client will call our callback but "success" is never printed since the client lost the race. My question here is, why don't we need to call clearTimeout(timer) but instantly return (due to if (called) return;)? We only call clearTimeout if the client wins the race but not when the client loses the race. Won't be "timeout" be printed every timeout milliseconds? Or does this only happen as long as the client does not call the callback, but when the callback is called by our client the scope gets destroyed anyways (socket.emit function finished executing) and therefore our timer gets destroyed as well?

Question 2: What is onSuccess.apply(this, args); making for a difference? Why not just calling onSuccess(args) directly here? Is it because of where the console.log should happen (with onSuccess.apply(this, args); making it log to the server's console and onSuccess(args) making it log to the client's console)?

I have to admit that are kind of basic JS concept questions but I never really had experienced them in practice (i only remember them from a book i read a while ago) to fully understand them until (hopefully) now

3
  • Won't be "timeout" be printed every timeout milliseconds? => I suspect there's a misconception or confusion here, so I want to clarify that setTimeout runs only once after N milliseconds. That's different from setInterval which runs every N milliseconds (but not used in this example). Commented Jan 18 at 15:40
  • Regarding "why don't we need to call clearTimeout(timer) but instantly return?", if this refers to the setTimeout callback code, then is makes no sense to clear a timeout that is already happening. It WOULD make, of course, sense in a setInterval. Commented Jan 18 at 15:54
  • You are right, I confused it with setInterval. Commented Jan 18 at 17:17

0

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.