Dakifiz
Dakifiz

Reputation: 13

Calling the function only once in a time

I have such a function on my website:

$("#search-label").on("keypress", function(e) {
  if(e.which == 13) {
    $('html, body').animate({
      scrollTop: $("#content").offset().top
    }, 2000);   
  }
});

Its task is to scroll to the selected element after press enter and it works fine, but the problem is that it can be called repeatedly in a short time and then the page gets stuck.

How to limit the possibility of calling it up to once every 10 seconds?

Thanks

Upvotes: 0

Views: 78

Answers (1)

Lakshya Raj
Lakshya Raj

Reputation: 1775

You can use a mix of a variable and a setTimeout to do this:

var scrollOK = true;

$("#search-label").on("keypress", function(e) {
  if((e.which == 13) && scrollOK) {
    $('html, body').animate({
      scrollTop: $("#content").offset().top
    }, 2000);   
    scrollOK = false;
    setTimeout(function(){ scrollOK=true; }, 10000);
  }
});

It uses scrollOK to make sure that scrolling is OK, and when it scrolls, then it sets it to false temporarily (temporarily because the setTimeout sets it back to true after 10 seconds, or 10000 milliseconds).

Edit: as @ChloeAnderson said, this may take up more resources than it should. This is a version that should be better:

var lastScrolled = 0;

$("#search-label").on("keypress", function(e) {
  if((e.which == 13) && (Date.now() >= (lastScrolled + 10000))) {
    $('html, body').animate({
      scrollTop: $("#content").offset().top
    }, 2000);   
    lastScrolled = Date.now();
  }
});

Upvotes: 3

Related Questions