【问题标题】:count the number of click in an interval of time统计一个时间间隔内的点击次数
【发布时间】:2011-09-28 17:07:40
【问题描述】:

如何计算一个时间间隔内的点击次数,例如:用户在 2 秒内完成了多少次点击?我知道如何计算点击次数,但我不知道如何计算时间

谢谢

【问题讨论】:

  • 您是指任何点击还是需要在特定元素上发生点击?

标签: javascript jquery count counter


【解决方案1】:

使用 setTimeout 函数

例如如果每次点击都会增加一个可变点击计数,您可以执行以下操作:

 function startCounting(){
    clickcount = 0;
    setTimeout(function(){alert("you made "+clickcount +" clicks!");}, 2000);
 }

【讨论】:

  • 在 startCounting 中设置 clickcount = 0
【解决方案2】:

HTML:

<button>Click me!</button>
<div id="status">Not Running</div>

JS:

var running = false,
    count = 0,
    run_for = 2000;

var end_counter = function() {
    if (running) {
        running = false;
        $("#status").text("Not Running");
        alert(count);
        started_at = 0;
    }
};
$('button').click(function() {
    if (running) {
        count++;
    } else {
        running = true;
        $("#status").text("Running");
        count = 1;
        setTimeout(end_counter, run_for);
    }
});

演示:http://jsfiddle.net/pXMxQ/2/

【讨论】:

    【解决方案3】:

    尝试使用超时清除检测点击的功能。使用 jQuery,试试这个:

    var clicks=0;
    function myClickFunction(event){
        clicks++;
    }
    $(function(){
        $("#something").bind("click",myClickFunction);
        setTimeout(function(){
            $("#something").unbind("click",myClickFunction);
            alert("You clicked "+clicks+" times.");
        },2000);
    });
    

    #something 替换为您希望检测到点击的元素的jQuery 选择器,并将alert 行替换为您自己的代码,该代码将在计时器用完后运行。 广告@m

    【讨论】:

      【解决方案4】:
      define a variable 
      attach click handler to element 
      set variable = 0
      start ur timer (setTimeout)
      increment variable on each click
      when timeout handler excutes, detach ur handler
      
      - OR - 
      
      define a variable for counter
      define a variable for doCounting
      set counter = 0, doCounting = true
      start ur timer (setTimeout)
      increment counter on each click if doCounting is true
      set doCounting = false when timeout handler executes
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-01
        • 1970-01-01
        • 2015-03-27
        • 1970-01-01
        • 1970-01-01
        • 2018-06-19
        • 1970-01-01
        相关资源
        最近更新 更多