Goal
I am trying to accomplish the following:
There is a slider/slidehow/carousel/whatever you want to call it, and I want it to register a touch event only once every 3s when you swipe to the right or left. For that I wrote the following code:
const debounce = (func, delay) => {
let debounceTimer
return function () {
const context = this
const args = arguments
clearTimeout(debounceTimer)
debounceTimer
= setTimeout(() => func.apply(context, args), delay)
}
}
if (location.pathname === "/") {
var backgroundElement = document.querySelector('.carousel');
hammer = new Hammer(backgroundElement)
hammer.on('panright panleft', function (event) {
//console.log(event.deltaX);
if (event.deltaX > 250) {
debounce(carousel.next(), 3000);
event.preventDefault();
}
if (event.deltaX < -250) {
debounce(carousel.previous(), 3000);
event.preventDefault();
}
Problem at hand
The problem is that if I keep on swiping after swiping it switches the slides continously back and forth it seems, so neither my debounce implementation or event.preventDefault();
appears to be working.
How do I fix this to have the intended functionality?
P.S. I would prefer not using RxJS just for this single functionality, I think that's an overkill.
UPDATE
I'm ok with using Lodash and I've tried implementing my code but I'm getting errors. My "new" code is:
if (location.pathname === "/") {
var backgroundElement = document.querySelector('.carousel');
hammer = new Hammer(backgroundElement)
hammer.on('panright panleft', function (event) {
console.log(event.deltaX);
if (event.deltaX > 250) {
//_.debounce((event)=> { carousel.next(); }, 1000);
_.debounce(nextSlide(), 1000);
//event.preventDefault();
}
if (event.deltaX < -250) {
//_.debounce((event)=> { carousel.previous(); }, 1000);
_.debounce(prevSlide(), 1000);
//event.preventDefault();
}
}
)};
My errors are (which trigger when I swipe on the carousel):
Uncaught TypeError: Expected a function
UPDATE 2
Heck, I'm so desperate that I'm even ok with using RxJS now, but my code does not work due to syntax mistakes. I would appreciate if an answer showed the mistake. My code prototype is the following:
if (location.pathname === "/") {
var backgroundElement = document.querySelector('.carousel');
hammer = new Hammer(backgroundElement)
hammer.on('panright panleft', function (event) {
console.log(event.deltaX);
if (event.deltaX > 250) {
//_.debounce((event)=> { carousel.next(); }, 1000);
_.debounce(nextSlide(), 1000);
//event.preventDefault();
}
if (event.deltaX < -250) {
//_.debounce((event)=> { carousel.previous(); }, 1000);
_.debounce(prevSlide(), 1000);
//event.preventDefault();
}
}
).pipe(
map((event.deltaX) => event.deltaX.debounceTime(1000))).subscribe(x => console.log(x);)
)
};
the console.log is only to test the filtering I would add the slide changing behaviour if it worked.