Locations: Use a reusable throttled function

This commit is contained in:
2020-02-26 16:05:35 +01:00
parent 42d67a4bc9
commit c9fd287609
2 changed files with 27 additions and 15 deletions

View File

@@ -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)
}
}

View File

@@ -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)
/*