From c9fd287609f4b399f59b9eefef271c7e92e440ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Pe=CC=81ault?= Date: Wed, 26 Feb 2020 16:05:35 +0100 Subject: [PATCH] Locations: Use a reusable throttled function --- src/functions.js | 31 ++++++++++++++++++++++++------- src/organisms/Locations.svelte | 11 +++-------- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/functions.js b/src/functions.js index 2eeac5f..d631b89 100644 --- a/src/functions.js +++ b/src/functions.js @@ -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) + } } diff --git a/src/organisms/Locations.svelte b/src/organisms/Locations.svelte index da3cf7f..35b80c9 100644 --- a/src/organisms/Locations.svelte +++ b/src/organisms/Locations.svelte @@ -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) /*