问题
I am chaging the background of the page using mousewheel. I only want to trigger the mousewheel event once 1000ms, so for that I am using a debounce function.
Before I added the debounce function and used e.preventDefault()
it prevented the scroll from working. However, now that I have added the debounce function this no longer works and the user can scroll the page again.
Please see code below.
$(document).ready(function() {
$(document).on('mousewheel DOMMouseScroll',debounce(function(e){
e.preventDefault();
//code to change the background image
}, 1000))
});
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
回答1:
then build it like this:
$(document).ready(function() {
var changeBackground = debounce(function(e){
//code to change the background image
}, 1000)
$(document).on('mousewheel DOMMouseScroll',debounce(function(e){
e.preventDefault();
changeBackground(e);
})
});
来源:https://stackoverflow.com/questions/39237942/debounce-function-means-e-preventdefault-on-mousewheel-no-longer-working