mock-socket icon indicating copy to clipboard operation
mock-socket copied to clipboard

Delay execution of dispatched events

Open piranna opened this issue 3 years ago • 5 comments

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Events from server to client needs to have some delay to mimic network delay.

Here is the diff that solved my problem:

diff --git a/node_modules/mock-socket/dist/mock-socket.js b/node_modules/mock-socket/dist/mock-socket.js
index 2478234..414d406 100644
--- a/node_modules/mock-socket/dist/mock-socket.js
+++ b/node_modules/mock-socket/dist/mock-socket.js
@@ -793,13 +793,16 @@ EventTarget.prototype.dispatchEvent = function dispatchEvent (event) {
     return false;
   }
 
-  listeners.forEach(function (listener) {
-    if (customArguments.length > 0) {
-      listener.apply(this$1, customArguments);
-    } else {
-      listener.call(this$1, event);
-    }
-  });
+  delay(function()
+  {
+    listeners.forEach(function (listener) {
+      if (customArguments.length > 0) {
+        listener.apply(this$1, customArguments);
+      } else {
+        listener.call(this$1, event);
+      }
+    });
+  })
 
   return true;
 };

This issue body was partially generated by patch-package.

piranna avatar May 01 '22 13:05 piranna

@piranna The dispatchEvent function is already called with the delay helper in the websocket. The server event can be called with delay manually in your code. Can you please give more details of your problem, what the exact place you need the delay?

Atrue avatar May 24 '22 14:05 Atrue

Just the part of the server event. I don't want to provide a manual delay on my code, I want the listeners to be executed at least in the next event loop when they are dispatched, not in the same one. This allows me to register some events in the WebSocket, as I would do normally in real code.

piranna avatar May 24 '22 19:05 piranna

Make sense, you can create a PR, but add the delay in the server's methods where it's needed, not in the dispatchEvent; It would be very helpful if you also provide a test or example that demonstrates the problem

Atrue avatar May 25 '22 06:05 Atrue

I think the server method is send(). Why dispatchEvent() is not the correct place? All the server-to-client events are going throught there, so it makes sense to me to add the "network transmission delay" there...

piranna avatar May 25 '22 06:05 piranna

All the events inside the library are going through dispatchEvent. If the event or the code should be delayed it's wrapped using the delay helper. See websocket.js for examples

Atrue avatar May 25 '22 06:05 Atrue