From ab5c8ff6bb0978dba8d1c3641b94652f0ae9405c Mon Sep 17 00:00:00 2001 From: evlist Date: Tue, 18 Oct 2022 14:24:21 +0200 Subject: [PATCH] Simple implementation of event handler throttling. --- src/components/map/Handlers.tsx | 53 ++++++++++++++++++------------- src/components/map/TiledLayer.tsx | 2 +- src/components/map/config.ts | 2 +- 3 files changed, 33 insertions(+), 24 deletions(-) diff --git a/src/components/map/Handlers.tsx b/src/components/map/Handlers.tsx index 460bc42..6d04db3 100644 --- a/src/components/map/Handlers.tsx +++ b/src/components/map/Handlers.tsx @@ -1,8 +1,7 @@ import react, { useState } from 'react'; -import { throttle } from 'lodash'; import { Point } from './types'; -import { handlersConfig } from './config'; import './Handler.css'; +import { handlersConfig } from './config'; export interface HandlersProperties { /**Transform the map: @@ -44,7 +43,11 @@ export const Handlers: react.FC = ( const initialMouseState = { down: false, starting: { x: -1, y: -1 }, + timestamp: 0, }; + + const [mouseState, setMouseState] = useState(initialMouseState); + const mouseLeaveHandler = (event: any) => { genericHandler(event); setMouseState(initialMouseState); @@ -55,6 +58,7 @@ export const Handlers: react.FC = ( setMouseState({ down: true, starting: { x: event.clientX, y: event.clientY }, + timestamp: 0, }); }; @@ -63,28 +67,33 @@ export const Handlers: react.FC = ( setMouseState(initialMouseState); }; - const mouseMoveHandler = throttle((event: any) => { - genericHandler(event); - if (mouseState.down) { - props.transformMap( - { - x: event.clientX - mouseState.starting.x, - y: event.clientY - mouseState.starting.y, - }, - null, - null - ); - setMouseState({ - down: true, - starting: { - x: event.clientX, - y: event.clientY, - }, - }); + const mouseMoveHandler = (event: any) => { + if ( + mouseState.down && + Date.now() - mouseState.timestamp > handlersConfig.mouseMoveThrottleDelay + ) { + genericHandler(event); + if (mouseState.down) { + props.transformMap( + { + x: event.clientX - mouseState.starting.x, + y: event.clientY - mouseState.starting.y, + }, + null, + null + ); + setMouseState({ + down: true, + starting: { + x: event.clientX, + y: event.clientY, + }, + timestamp: Date.now(), + }); + } } - }, handlersConfig.mouseMoveThrottleDelay); + }; - const [mouseState, setMouseState] = useState(initialMouseState); return (