Locations: Use a reusable throttled function
This commit is contained in:
@@ -5,13 +5,30 @@ import { apiEndpoints } from './store'
|
||||
** Debounce function with a delay
|
||||
** (For scrolling or other resource demanding behaviors)
|
||||
*/
|
||||
export const debounce = (callback, wait) => {
|
||||
// let timeout
|
||||
// return (...args) => {
|
||||
// const context = this
|
||||
// clearTimeout(timeout)
|
||||
// timeout = setTimeout(() => callback.apply(context, args), wait)
|
||||
// }
|
||||
export const debounce = (callback, wait, immediate = false) => {
|
||||
let timeout = null
|
||||
return function () {
|
||||
const callNow = immediate && !timeout
|
||||
const next = () => callback.apply(this, arguments)
|
||||
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
|
||||
const transitionDuration = 800
|
||||
let clickOrigin = Date.now()
|
||||
let filterLocations
|
||||
let continentsToDisplay = []
|
||||
let continentsFiltered = []
|
||||
@@ -25,14 +24,10 @@
|
||||
continentsFiltered = [...continentsToDisplay]
|
||||
|
||||
// Filter by continent
|
||||
// detects if click difference if too short
|
||||
const toggleContinents = (event, continent) => {
|
||||
if (Date.now() - clickOrigin < transitionDuration) {
|
||||
return
|
||||
}
|
||||
// Detects if click difference if too short with a throttled function
|
||||
const toggleContinents = fn.throttled((event, continent) => {
|
||||
continentsFiltered = (!continent) ? [...continentsToDisplay] : [continent]
|
||||
clickOrigin = Date.now()
|
||||
}
|
||||
}, transitionDuration)
|
||||
|
||||
|
||||
/*
|
||||
|
||||
Reference in New Issue
Block a user