每5秒仅对事件做出一次反应 [英] React to an event only once every 5 seconds

查看:66
本文介绍了每5秒仅对事件做出一次反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用setInterval()运行一个函数,然后单击.我只想每五秒钟运行一次somefunction()函数.

I'm trying to run a function using setInterval() and click. I want run the function somefunction() only once in every five seconds when i click.

这是我的代码:

function somefunction(){ // do something }

setInterval(function(){
  $('#division').one("click",function(){
    somefunction();
  });
}, 5000);

这里的问题是,事件setInterval()正在排队,并说30秒后功能somefunction();最多运行6次(6次单击).

The issue here is, the event setInterval() is queuing up and say after 30 secs the function somefunction(); runs upto 6 times (for 6 clicks).

但是我希望它只运行一次并等待接下来的5秒钟.

But I want it to run only once and wait for next 5 seconds.

我尝试了.stop().dequeue().clearqueue(),尽管没有任何效果.

I have tried .stop(), .dequeue() and .clearqueue() although nothing worked.

感谢您的帮助!

推荐答案

如何忽略少于5秒的每次点击?

How about ignoring every click that has been less than 5 seconds ago?

function somefunction() { /* do something */ }

$('#division').on("click", function () {
  var lastClicked = $(this).data("lastClicked") || 0;

  if (new Date() - lastClicked >= 5000) {
    $(this).data("lastClicked", new Date());
    somefunction();
  }
});

或者,根据最后一次安排点击,只要计划了一项操作,就忽略所有点击:

Alternatively, schedule the click in accordance to the last one, ignore all clicks as long as an action is scheduled:

function somefunction() { /* do something */ }

$('#division').on("click", function () {
  var $this = $(this),
      lastClicked = $this.data("lastClicked") || 0,
      isScheduled = $this.is(".scheduled");

  if (!isScheduled) {
    $this.addClass("scheduled");
    setTimeout(function () {
      somefunction()
      $this.removeClass("scheduled").data("lastClicked", new Date());
    }, Math.max(0, 5000 - (new Date() - lastClicked)));
  }
});

请参阅: http://jsfiddle.net/Tomalak/ZXfMQ/1/

这篇关于每5秒仅对事件做出一次反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆