【问题标题】:Calling the function only once in a time一次只调用一次函数
【发布时间】:2021-04-15 22:16:00
【问题描述】:

我的网站上有这样的功能:

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

它的任务是回车后滚动到选中的元素,效果很好,但问题是短时间内重复调用会卡住。

如何限制每 10 秒调用一次的可能性?

谢谢

【问题讨论】:

标签: javascript html jquery


【解决方案1】:

您可以混合使用变量和setTimeout 来执行此操作:

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);
  }
});

它使用scrollOK 来确保滚动正常,当它滚动时,它会暂时将其设置为false(暂时因为setTimeout 在10 秒后将其设置回true,即10000毫秒)。

编辑:正如@ChloeAnderson 所说,这可能会占用更多资源。这是一个应该更好的版本:

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();
  }
});

【讨论】:

  • 请不要使用间隔(或超时)进行冷却,使用performance.now() 等时间戳没有任何问题,因为它们只会根据请求进行评估。
  • @ChloeAnderson:我不明白使用setTimeout 有什么问题。它似乎非常适合这种情况。
  • 看起来,也可能是,但更多的性能设置是使用时间戳。与比较两个整数(即时间戳)相比,您依靠间隔使用的资源更多。
  • @ChloeAnderson:好的。我在我的问题中添加了您的解决方案。谢谢!
猜你喜欢
  • 2017-06-14
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 2018-07-13
  • 2012-08-23
相关资源
最近更新 更多