Recently, I encountered an issue with a JavaScript code that swaps background images on scroll down. To address the problem with debounce, I ended up setting different debounce times for various browsers (I am aware this is not the ideal solution, but it's getting the job done for now as I am still new to JavaScript).
However, another hurdle emerged when scrolling on my phone - it was happening too quickly. In an attempt to resolve this, I tried setting a different debounce time for screens smaller than 480px, but unfortunately, it didn't work as expected. It seems like the "browser if" condition is overriding the "width if" condition, and I'm uncertain about how to rectify this.
Below is the current code snippet (admittedly, it's not the cleanest due to my novice status in JavaScript):
$(document).ready(function(){
var isFirefox = typeof InstallTrigger !== 'undefined';
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !isOpera;
var numberofscroll = 0;
var lastScrollTop = 0;
var dontHandle = false;
$("#home").scroll(function () {
if (dontHandle) return;
dontHandle = true;
var st = $(this).scrollTop();
(st > lastScrollTop) ? numberofscroll++ : numberofscroll--;
console.log(numberofscroll);
console.log(lastScrollTop);
console.log(st);
if (numberofscroll<2){
change_background2(numberofscroll);
}
else if (numberofscroll<3){
change_background3(numberofscroll);
}
else if (numberofscroll<4){
change_background4(numberofscroll);
}
else if (numberofscroll<5){
change_background5(numberofscroll);
}
else if (numberofscroll<6){
change_background6(numberofscroll);
}
lastScrollTop = st;
if (isFirefox == true) {
window.setTimeout(function() {
dontHandle = false;
}, 150);
}else if (isOpera == true) {
window.setTimeout(function() {
dontHandle = false;
}, 10);
}else if (isChrome == true) {
window.setTimeout(function() {
dontHandle = false;
}, 10);
}else if ($(window).width() < 480){
window.setTimeout(function() {
dontHandle = false;
}, 500);
}else {
window.setTimeout(function() {
dontHandle = false;
}, 50);
}
});
/images swaping code here/
});
I also attempted to incorporate the following addition which unfortunately did not yield the desired outcome:
if ($(window).width() < 480){
window.setTimeout(function() {
dontHandle = false;
}, 500);
}else {
window.setTimeout(function() {
dontHandle = false;
}, 50);
}