How to prevent spam listening onclick?

This is a new problem for me, and I could not find any information about it.

I have a simple onclick listener that performs smooth scrolling to the target on the page. Here is the code below:

$(".nav-scroll").click(function (event) {
    var ID = this.hash;
    //has a few extra conditionals here specific to the page
    $('html,body').animate({ scrollTop: $(ID).offset().top }, 1000);
});

Ultimately, the scenario is that it takes time to complete this function. Not much time, but it really does add up if someone spammed the link on the page and the browser started queuing function calls. Now spam is an extreme case, but even after 3 or 4 consecutive clicks it prevents the user from working until they can scroll down the page, because the page tries to scroll them to the target 3 or 4 times.

All my research was able to check if there is already an event listener in the window, which is already found here: JavaScript - how to check if an event is added or listing all event listeners on an element similar here: jQuery find event handlers registered with the object , but do not check anything to see if something is currently running.

Is it possible to prevent this side effect by dropping all previous listener calls in the middle of the page before execution or in another way? Or is this something JavaScript doesn't offer? If so, are there strategies to get around this, for example, to check if this function performs?

+4
source share
3

, , , , , , . , stop:

$(".nav-scroll").click(function (event) {
    var ID = this.hash;
    //has a few extra conditionals here specific to the page

    //call stop to kill old animations
    $('html,body').stop().animate({ scrollTop: $(ID).offset().top }, 1000);
});

, , , , , .

+2

:

var debounce = false;
$(".nav-scroll").click(function (event) {
    if (debounce) return;
    debounce = true;
    var ID = this.hash;
    //has a few extra conditionals here specific to the page
    $('html,body').animate({ scrollTop: $(ID).offset().top}, 1000, function() {debounce=false;});
});

, onclick, , .

+1

onClick , .

:

// lodash is defined here as _

var animationTime = 1000;

var scrollTo = _.throttle(function (event) {
    var ID = this.hash;
    //has a few extra conditionals here specific to the page
    $('html,body').animate({ scrollTop: $(ID).offset().top }, animationTime);
}, animationTime);

$(".nav-scroll").click(scrollTo);

This case on the first user call causes a call, but if it clicks again within a period of time (1000 ms), the function will not be executed again. Only after the time has passed, the user can call the function again.

Here you can find the documentation for the lodash throttle: https://lodash.com/docs#throttle

+1
source

Source: https://habr.com/ru/post/1628167/


All Articles