Locations: Use a reusable throttled function
This commit is contained in:
@@ -5,13 +5,30 @@ import { apiEndpoints } from './store'
|
|||||||
** Debounce function with a delay
|
** Debounce function with a delay
|
||||||
** (For scrolling or other resource demanding behaviors)
|
** (For scrolling or other resource demanding behaviors)
|
||||||
*/
|
*/
|
||||||
export const debounce = (callback, wait) => {
|
export const debounce = (callback, wait, immediate = false) => {
|
||||||
// let timeout
|
let timeout = null
|
||||||
// return (...args) => {
|
return function () {
|
||||||
// const context = this
|
const callNow = immediate && !timeout
|
||||||
// clearTimeout(timeout)
|
const next = () => callback.apply(this, arguments)
|
||||||
// timeout = setTimeout(() => callback.apply(context, args), wait)
|
clearTimeout(timeout)
|
||||||
// }
|
timeout = setTimeout(next, wait)
|
||||||
|
if (callNow) next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Throttle function with a delay
|
||||||
|
** (Throttling enforces a maximum number of times a function can be called over time, as in 'execute this function at most once every 100 milliseconds)
|
||||||
|
*/
|
||||||
|
export function throttled (fn, delay) {
|
||||||
|
let lastCall = 0
|
||||||
|
return function (...args) {
|
||||||
|
const now = (new Date).getTime()
|
||||||
|
if (now - lastCall < delay) return
|
||||||
|
lastCall = now
|
||||||
|
return fn(...args)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,6 @@
|
|||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
const transitionDuration = 800
|
const transitionDuration = 800
|
||||||
let clickOrigin = Date.now()
|
|
||||||
let filterLocations
|
let filterLocations
|
||||||
let continentsToDisplay = []
|
let continentsToDisplay = []
|
||||||
let continentsFiltered = []
|
let continentsFiltered = []
|
||||||
@@ -25,14 +24,10 @@
|
|||||||
continentsFiltered = [...continentsToDisplay]
|
continentsFiltered = [...continentsToDisplay]
|
||||||
|
|
||||||
// Filter by continent
|
// Filter by continent
|
||||||
// detects if click difference if too short
|
// Detects if click difference if too short with a throttled function
|
||||||
const toggleContinents = (event, continent) => {
|
const toggleContinents = fn.throttled((event, continent) => {
|
||||||
if (Date.now() - clickOrigin < transitionDuration) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
continentsFiltered = (!continent) ? [...continentsToDisplay] : [continent]
|
continentsFiltered = (!continent) ? [...continentsToDisplay] : [continent]
|
||||||
clickOrigin = Date.now()
|
}, transitionDuration)
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
Reference in New Issue
Block a user