Reputation: 123
I have written a jQuery script that will scroll in/out on an element when the scroll wheel is activated.
Unfortunately the scroll itself is quite slow, so if a user rolls the mousewheel multiple times then the backlog of scrolls can take a long time to catch up. I want to set it so that there is a half second delay between each scroll that is captured and the next scroll can only be triggered after that half second has elapsed, and any additional scrolls in the meantime should be ignored.
In the below script, if someone were to keep scrolling over the box I would only want the counter to increase every half second regardless of how fast they were scrolling. I have no idea how to do this so any help would be greatly appreciated. Thanks!
$("#boxScroll").bind('mousewheel', function() {
var countPastScrolls = parseInt($("#countScrolls").text(),10)
$("#countScrolls").text(countPastScrolls+1)
})
.box {
width: 50px;
height: 50px;
border: 1px solid black;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<DIV class="box" id="boxScroll"></DIV>
Count of scrolls: <DIV id="countScrolls">0</DIV>
Upvotes: 1
Views: 189
Reputation: 337560
To achieve this you can use a timeout to debounce the scroll counter so that it only fires once for every 500ms of scrolling. Try this:
$("#boxScroll").on('mousewheel', function() {
var $box = $(this);
if (!$box.data('disable-count')) {
$box.data('disable-count', true)
$("#countScrolls").text(function(i, t) {
return parseInt(t, 10) + 1;
});
setTimeout(function() {
$box.data('disable-count', false);
}, 500);
}
})
.box {
width: 50px;
height: 50px;
border: 1px solid black;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="box" id="boxScroll"></div>
Count of scrolls:
<div id="countScrolls">0</div>
Upvotes: 1