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 { 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<HandlersProperties> = (
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<HandlersProperties> = (
setMouseState({
down: true,
starting: { x: event.clientX, y: event.clientY },
timestamp: 0,
});
};
@ -63,7 +67,11 @@ export const Handlers: react.FC<HandlersProperties> = (
setMouseState(initialMouseState);
};
const mouseMoveHandler = throttle((event: any) => {
const mouseMoveHandler = (event: any) => {
if (
mouseState.down &&
Date.now() - mouseState.timestamp > handlersConfig.mouseMoveThrottleDelay
) {
genericHandler(event);
if (mouseState.down) {
props.transformMap(
@ -80,11 +88,12 @@ export const Handlers: react.FC<HandlersProperties> = (
x: event.clientX,
y: event.clientY,
},
timestamp: Date.now(),
});
}
}, handlersConfig.mouseMoveThrottleDelay);
}
};
const [mouseState, setMouseState] = useState(initialMouseState);
return (
<div
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 { Rectangle, TileFactory, TileKeyObject } from './types';

View File

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