Skip to content

Commit

Permalink
added throttle on composing
Browse files Browse the repository at this point in the history
  • Loading branch information
dendidibe committed Oct 5, 2023
1 parent 10a9c28 commit 293855f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
19 changes: 12 additions & 7 deletions client-web/src/pages/ChatInRoom/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import { useSnackbar } from "../../context/SnackbarContext";
import { createMainMessageForThread } from "../../utils/createMessage";
import Dompurify from "dompurify";
import { LeaveRoomButton } from "../../components/Chat/LeaveRoomButton";
import { throttle } from "../../utils/throttle";

export type IMessagePosition = {
position: MessageModel["position"];
Expand Down Expand Up @@ -401,14 +402,19 @@ export function ChatInRoom() {
}
setFileUploading(false);
};
const sendThrottledComposing = useRef(
throttle(() => {
xmpp.isComposing(
user.walletAddress,
roomData.jid,
user.firstName + " " + user.lastName
);
}, 500)
);

const setMessage = (value) => {
const setMessage = (value: string) => {
setMyMessage(value);
xmpp.isComposing(
user.walletAddress,
roomData.jid,
user.firstName + " " + user.lastName
);
sendThrottledComposing.current();
};

const handlePaste = (event: any) => {
Expand All @@ -423,7 +429,6 @@ export function ChatInRoom() {
};

useEffect(() => {

const timeoutId = setTimeout(() => {
xmpp.pausedComposing(user.walletAddress, roomData?.jid);
}, 1000);
Expand Down
29 changes: 29 additions & 0 deletions client-web/src/utils/throttle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export const throttle = <T extends (...args: any[]) => void>(
func: T,
delay: number
): T => {
let lastInvokeTime = 0;
let timeoutId: NodeJS.Timeout | null = null;

return ((...args: any[]) => {
const now = Date.now();
const timeSinceLastInvoke = now - lastInvokeTime;

const invoke = () => {
lastInvokeTime = Date.now();
func(...args);
};

if (timeSinceLastInvoke >= delay) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
invoke();
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
invoke();
}, delay - timeSinceLastInvoke);
}
}) as T;
};

0 comments on commit 293855f

Please sign in to comment.