diff --git a/src/utils/debounce.js b/src/utils/debounce.js new file mode 100644 index 000000000..43b400647 --- /dev/null +++ b/src/utils/debounce.js @@ -0,0 +1,22 @@ +/* global setTimeout, clearTimeout */ +/* eslint-disable consistent-this, func-names */ +export default function debounce(func, delay) { + let _this; + let _arguments; + let timeout; + + const executeNow = () => { + timeout = null; + return func.apply(_this, _arguments); + }; + + return function() { + _this = this; + _arguments = arguments; + + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(executeNow, delay); + }; +} diff --git a/src/utils/map-controller.js b/src/utils/map-controller.js index 206c2aa71..7a165a95c 100644 --- a/src/utils/map-controller.js +++ b/src/utils/map-controller.js @@ -22,6 +22,7 @@ import MapState from './map-state'; import {LinearInterpolator} from './transition'; import TransitionManager, {TRANSITION_EVENTS} from './transition-manager'; +import debounce from './debounce'; import type {MjolnirEvent} from 'mjolnir.js'; @@ -75,6 +76,7 @@ export default class MapController { constructor() { (this: any).handleEvent = this.handleEvent.bind(this); + (this: any)._onWheelEnd = debounce(this._onWheelEnd, 100); } /** @@ -316,11 +318,15 @@ export default class MapController { const newMapState = this.mapState.zoom({pos, scale}); this.updateViewport(newMapState, NO_TRANSITION_PROPS, {isZooming: true}); - // This is a one-off event, state should not persist - this.setState({isZooming: false}); + // Wheel events are discrete, let's wait a little before resetting isZooming + this._onWheelEnd(); return true; } + _onWheelEnd() { + this.setState({isZooming: false}); + } + // Default handler for the `pinchstart` event. _onPinchStart(event: MjolnirEvent) { const pos = this.getCenter(event); diff --git a/test/src/utils/debounce.spec.js b/test/src/utils/debounce.spec.js new file mode 100644 index 000000000..41445b102 --- /dev/null +++ b/test/src/utils/debounce.spec.js @@ -0,0 +1,24 @@ +/* global setTimeout */ +import test from 'tape-catch'; +import debounce from 'react-map-gl/utils/debounce'; + +test('debounce', t => { + const funcCalled = []; + + function func(x) { + funcCalled.push({context: this, arg: x}); + } + + const debounced = debounce(func, 1); + + debounced.call('0', 0); + debounced.call('1', 1); + debounced.call('2', 2); + + t.deepEquals(funcCalled, [], 'function is not called yet'); + + setTimeout(() => { + t.deepEquals(funcCalled, [{context: '2', arg: 2}], 'function is called once'); + t.end(); + }, 5); +}); diff --git a/test/src/utils/index.js b/test/src/utils/index.js index c8684cd7f..6d61aa65e 100644 --- a/test/src/utils/index.js +++ b/test/src/utils/index.js @@ -3,3 +3,4 @@ import './map-state.spec'; import './map-constraints.spec'; import './dynamic-position.spec'; import './transition-manager.spec'; +import './debounce.spec';