Simple implementation of event handler throttling.

This commit is contained in:
Eric van der Vlist 2022-10-18 14:24:21 +02:00
parent 963f6037ca
commit ab5c8ff6bb
3 changed files with 33 additions and 24 deletions

View File

@ -1,8 +1,7 @@
import react, { useState } from 'react'; import react, { useState } from 'react';
import { throttle } from 'lodash';
import { Point } from './types'; import { Point } from './types';
import { handlersConfig } from './config';
import './Handler.css'; import './Handler.css';
import { handlersConfig } from './config';
export interface HandlersProperties { export interface HandlersProperties {
/**Transform the map: /**Transform the map:
@ -44,7 +43,11 @@ export const Handlers: react.FC<HandlersProperties> = (
const initialMouseState = { const initialMouseState = {
down: false, down: false,
starting: { x: -1, y: -1 }, starting: { x: -1, y: -1 },
timestamp: 0,
}; };
const [mouseState, setMouseState] = useState(initialMouseState);
const mouseLeaveHandler = (event: any) => { const mouseLeaveHandler = (event: any) => {
genericHandler(event); genericHandler(event);
setMouseState(initialMouseState); setMouseState(initialMouseState);
@ -55,6 +58,7 @@ export const Handlers: react.FC<HandlersProperties> = (
setMouseState({ setMouseState({
down: true, down: true,
starting: { x: event.clientX, y: event.clientY }, starting: { x: event.clientX, y: event.clientY },
timestamp: 0,
}); });
}; };
@ -63,7 +67,11 @@ export const Handlers: react.FC<HandlersProperties> = (
setMouseState(initialMouseState); setMouseState(initialMouseState);
}; };
const mouseMoveHandler = throttle((event: any) => { const mouseMoveHandler = (event: any) => {
if (
mouseState.down &&
Date.now() - mouseState.timestamp > handlersConfig.mouseMoveThrottleDelay
) {
genericHandler(event); genericHandler(event);
if (mouseState.down) { if (mouseState.down) {
props.transformMap( props.transformMap(
@ -80,11 +88,12 @@ export const Handlers: react.FC<HandlersProperties> = (
x: event.clientX, x: event.clientX,
y: event.clientY, y: event.clientY,
}, },
timestamp: Date.now(),
}); });
} }
}, handlersConfig.mouseMoveThrottleDelay); }
};
const [mouseState, setMouseState] = useState(initialMouseState);
return ( return (
<div <div
className='handler' className='handler'

View File

@ -1,4 +1,4 @@
import react, { useEffect, useRef } from 'react'; import react, { useRef } from 'react';
import { range, isEqual } from 'lodash'; import { range, isEqual } from 'lodash';
import { Rectangle, TileFactory, TileKeyObject } from './types'; import { Rectangle, TileFactory, TileKeyObject } from './types';

View File

@ -1,5 +1,5 @@
/**The handlers configuration */ /**The handlers configuration */
export const handlersConfig = { export const handlersConfig = {
/**Controls the activity of the mouse mouse event */ /**Controls the activity of the mouse mouse event */
mouseMoveThrottleDelay: 1000, mouseMoveThrottleDelay: 50,
} }