最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Socket.io code snippet explained (JavaScript setTimeout and function.apply) - Stack Overflow

programmeradmin2浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论