当警报出现时,停止按下按钮的人

时间:2015-06-17 04:22:51

标签: javascript jquery

我在这里创建/创建了以下内容:http://jsfiddle.net/Tomzen/hu720awa/ 但是,如果用户单击“Click!”,则会偶尔弹出一个问题。警报出现时按钮(告诉您停止点击),计时器将重新启动,结果将被重置(您将看到是否使用它)

除了创建一个在警报弹出前几毫秒禁止按下按钮的计时器,我无法找到解决方法。 有人可以看一下,看看他们之前是否见过这种事情?

$(document).ready(function () {
score = 0;
stop = 0;
$("#test").html("Score: " + score + "<br>Average: 0<br>You have 5 seconds to click as fast as you can. Your time will start on the first click.");
$("counting").html("test");

$("#button").click(function () {
    score = score + 1;
    average = score / 5;
    $("#test").html("Score: " + score + "<br>Average: " + average + " cps.<br>You have 5 seconds to click as fast as you can.");
    startTimer();
});

function startTimer() {
    if (stop === 0) {
        stop = stop + 1;
        var counter = 0;
        var interval = setInterval(function () {
            counter++;
            display = 5 - counter;
            $("#button").html("CLICK! (" + display + " secs)");
            if (counter == 5) {
                alert("It's been 5 seconds, stop clicking now.");
                clearInterval(interval);
                stop = 0;
                endscore = score;
                score = 0;
                $("#test").html("You clicked " + endscore + " times, in 5 seconds.<br>Your average click speed was " + average + " clicks per second.<br>Start clicking again to retry and get a better score!");
                $("#button").html("CLICK! (5 secs)");
            }
        }, 1000);
    }
}
});

代码是JQuery和JS,也使用在JSFiddle上找到的HTML和CSS,并且可能存在无用的代码。

1 个答案:

答案 0 :(得分:1)

我能够重现你的问题。在计时器到达0之前,单击并按住鼠标键。警报会出现。点击键盘上的Enter键以关闭警告框。然后释放鼠标。 (这是一种老式的方法,可以在开发控制台之前右键单击禁用脚本。)再次单击将注册,计数器将重新开始。

为防止这种情况,请更改

$("#button").click(function () {

$("#button").on("mousedown", function () {

忽略与点击相关联的鼠标操作。

stop = 0;之后您有alert(),因此警报出现时无法再次点击会触发if (stop === 0) {中的逻辑,仅触发mouseup事件后的逻辑警报被驳回将允许这种情况发生。

演示: JSFiddle