jQuery单击后阻止函数继续前进

时间:2019-11-22 10:04:05

标签: javascript jquery

let total = 0;
let average = 0;
$(document).ready(function() {

  let tryNbr = 1;
  let timeDiff = null;

  let startSession = $(".startSession");
  let titleInfo = $(".title-info");
  let introP = $(".intro p");
  let highlightBlue = $(".highlight-blue");
  let totalTries = $('#totalTries');
  let clicked = 0;

  $(".average-title").hide();

  startSession.click(function(e) {

    e.stopPropagation();
    e.preventDefault();
    titleInfo.html("Wait for the green...");

    introP.hide();

    startSession.hide();

    waitGreenTime();
  });


  function waitGreenTime() {

    $(".average-title").hide();
    highlightBlue.off();

    highlightBlue.css("cursor", "pointer");
    highlightBlue.animate({
      height: "600",
    });

    let waitGreen = Math.floor(Math.random() * 4 + 2);

    console.log("Green will be shown in:  " + waitGreen + "s");


    highlightBlue.click(function() {
      tooSoon();
    });

    setTimeout(showGreen, waitGreen * 1000)

  }

  function showGreen() {
    highlightBlue.off();
    titleInfo.hide();
    highlightBlue.css("background-color", "green");
    startTime = new Date();
    highlightBlue.click(function() {
      endTime = new Date();
      timeDiff = endTime - startTime;
      console.log(timeDiff);
      results(timeDiff);
    });
  }

  function results(timeDiff) {

    highlightBlue.off();

    titleInfo.html("Your reaction time: " + timeDiff + "ms");
    titleInfo.show();

    introP.html("To see your previous stats check the table down below.").show();;

    startSession.show();

    highlightBlue.animate({
      height: "327",
    });

    highlightBlue.css({
      "background-color": "#131620",
      "cursor": "default"
    });

    total = total + timeDiff;
    console.log("total is " + total);
    average = total / tryNbr;
    console.log("avg is " + average);

    $("#average").text("");
    $("#average").append(average + "ms " + " | ");

    let tr = $("<tr></tr>");
    let td1 = $("<td></td>").text(timeDiff);
    let td2 = $("<td></td>").text("#" + tryNbr);
    tr.append(td1, td2);

    let tableTrRef = $(".table-stats tbody");

    tableTrRef.append(tr).hide().fadeIn();

    totalTries.text("").append("Tries: " + tryNbr);

    $(".average-title").fadeIn();

    tryNbr++;
  }

  function tooSoon() {
    titleInfo.html("You pressed too soon!");
    startSession.fadeIn();
    introP.html("Before you press, please wait for the green background to show. Nice try though!").fadeIn();
    highlightBlue.animate({
      height: "327",
    });
  }

});
.average-title {
  text-align: center;
  font-size: 15px;
  color: #ff969f !important;
  margin-top: 30px;
  margin-bottom: 0;
}

.table-stats {
  width: 50%;
  color: white;
  margin-left: auto;
  margin-right: auto;
  margin-top: 50px;
  background-color: #131620;
  text-align: center;
}

.table-stats th {
  border-bottom: 1px solid whitesmoke;
  font-size: 30px;
  width: 50%;
}

th:first-child {
  border-right: 1px solid whitesmoke;
}

td:nth-child(odd) {
  border-right: 1px solid whitesmoke;
}

td {
  border-bottom: 1px solid whitesmoke;
  font-size: 25px;
}

.footer-basic {
  margin-top: 340px;
  background-color: #131620 !important;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
  <title>Reactionz</title>
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="assets/css/Footer-Basic.css">
  <link rel="stylesheet" href="assets/css/Highlight-Blue.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
  <link rel="stylesheet" href="assets/css/Navigation-Clean.css">
  <link rel="stylesheet" href="assets/css/styles.css">
</head>

<body style="background-color: #272E42;">
  <nav class="navbar navbar-light navbar-expand-md navigation-clean" style="background-color: #272e42;">
    <div class="container"><a class="navbar-brand" href="#" style="color: #ff969f;font-size: 20px;">Reactionz</a><button data-toggle="collapse" class="navbar-toggler" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="navbar-toggler-icon"></span></button>
      <div class="collapse navbar-collapse" id="navcol-1">
        <ul class="nav navbar-nav ml-auto">
          <li class="nav-item" role="presentation"><a class="nav-link active" href="#">Home</a></li>
          <li class="nav-item" role="presentation"><a class="nav-link" href="#">About</a></li>
        </ul>
      </div>
    </div>
  </nav>
  <div class="highlight-blue" style="background-color: #131620;">
    <div class="container">
      <div class="intro">
        <h2 class="text-center title-info">How fast do you react?</h2>
        <p class="text-center">Measure your ability to react. CS: GO professionals have an average score of 150ms and the average human fall between 200-250ms.<br><br></p>
      </div>
      <div data-bs-hover-animate="tada" class="buttons"><a class="btn btn-primary wobble animated startSession" role="button" href="#" style="background-color: #ff969f;">React</a></div>
      <p class="average-title">Your average: <span id="average"></span><span id="totalTries"></span></p>
    </div>
  </div>

  <table class="table-stats">
    <tr>
      <th>Time (ms)</th>
      <th>Try</th>
    </tr>
  </table>
  <div class="footer-basic" style="background-color: #272e42;filter: blur(0px) grayscale(0%);">
    <footer>
      <ul class="list-inline">
        <li class="list-inline-item"><a href="#" style="filter: brightness(200%) contrast(0%);">Home</a></li>
        <li class="list-inline-item"></li>
        <li class="list-inline-item"><a href="#" style="filter: blur(0px) brightness(200%) contrast(0%) grayscale(0%);">About</a></li>
        <li class="list-inline-item"></li>
        <li class="list-inline-item"><a href="#" style="filter: brightness(200%) contrast(0%);">Privacy Policy</a></li>
      </ul>
      <p class="copyright">Reactionz © 2019</p>
    </footer>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="assets/bootstrap/js/bootstrap.min.js"></script>
  <script src="assets/js/bs-animation.js"></script>
  <script src="assets/js/script.js"></script>
</body>

</html>

我正在尝试创建一个反应时间测试应用程序。我遇到的问题是,如果用户很快在div上按,则应该阻止该用户执行下一个功能。

我的原始想法是,如果用户过早按下div,则应将其强制使用tooSoon()功能。它正在工作,但是问题是最后一行也已执行,我知道为什么,但是我不知道如何防止它。

还有其他方法吗?

function waitGreenTime() {
  $(".average-title").hide();
  highlightBlue.off();
  highlightBlue.css("cursor", "pointer");
  highlightBlue.animate({
    height: "600",
  });

  let waitGreen = Math.floor(Math.random() * 4 + 2);
  console.log("Green will be shown in:  " + waitGreen + "s");

  highlightBlue.click(function() {
    tooSoon();
  });

  setTimeout(showGreen, waitGreen * 1000);
}

2 个答案:

答案 0 :(得分:1)

这里的问题是因为click和setTimeout是异步的。 您可以在他们之间共享价值:

function waitGreenTime() {

   $(".average-title").hide();
      let isTooSoon = false;
      highlightBlue.off();
      highlightBlue.css("cursor", "pointer");
      highlightBlue.animate({
        height: "600",
      });

      let waitGreen = Math.floor(Math.random() * 4 + 2);
      console.log("Green will be shown in:  " + waitGreen + "s");

      highlightBlue.click(() => {
        isTooSoon = true;
        tooSoon();
      });

      setTimeout(()=>{
        if(isTooSoon===false){
          showGreen();
        }
      }, waitGreen * 1000);
}

答案 1 :(得分:1)

事件在预定时间之前发生时,您可以使用clearTimeout()

var timoutID = -1; 
highlightBlue.click(function() {
   tooSoon();
   clearTimeout(timeoutID);
});
timeoutID = setTimeout(showGreen, waitGreen * 1000)

let total = 0;
let average = 0;
$(document).ready(function() {

  let tryNbr = 1;
  let timeDiff = null;

  let startSession = $(".startSession");
  let titleInfo = $(".title-info");
  let introP = $(".intro p");
  let highlightBlue = $(".highlight-blue");
  let totalTries = $('#totalTries');
  let clicked = 0;

  $(".average-title").hide();

  startSession.click(function(e) {

    e.stopPropagation();
    e.preventDefault();
    titleInfo.html("Wait for the green...");

    introP.hide();

    startSession.hide();

    waitGreenTime();
  });


  function waitGreenTime() {

    $(".average-title").hide();
    highlightBlue.off();

    highlightBlue.css("cursor", "pointer");
    highlightBlue.animate({
      height: "600",
    });

    let waitGreen = Math.floor(Math.random() * 4 + 2);

    console.log("Green will be shown in:  " + waitGreen + "s");

    var timoutID = -1;

    highlightBlue.click(function() {
      tooSoon();
      clearTimeout(timeoutID);
    });

    timeoutID = setTimeout(showGreen, waitGreen * 1000);

  }

  function showGreen() {
    highlightBlue.off();
    titleInfo.hide();
    highlightBlue.css("background-color", "green");
    startTime = new Date();
    highlightBlue.click(function() {
      endTime = new Date();
      timeDiff = endTime - startTime;
      console.log(timeDiff);
      results(timeDiff);
    });
  }

  function results(timeDiff) {

    highlightBlue.off();

    titleInfo.html("Your reaction time: " + timeDiff + "ms");
    titleInfo.show();

    introP.html("To see your previous stats check the table down below.").show();;

    startSession.show();

    highlightBlue.animate({
      height: "327",
    });

    highlightBlue.css({
      "background-color": "#131620",
      "cursor": "default"
    });

    total = total + timeDiff;
    console.log("total is " + total);
    average = total / tryNbr;
    console.log("avg is " + average);

    $("#average").text("");
    $("#average").append(average + "ms " + " | ");

    let tr = $("<tr></tr>");
    let td1 = $("<td></td>").text(timeDiff);
    let td2 = $("<td></td>").text("#" + tryNbr);
    tr.append(td1, td2);

    let tableTrRef = $(".table-stats tbody");

    tableTrRef.append(tr).hide().fadeIn();

    totalTries.text("").append("Tries: " + tryNbr);

    $(".average-title").fadeIn();

    tryNbr++;
  }

  function tooSoon() {
    titleInfo.html("You pressed too soon!");
    startSession.fadeIn();
    introP.html("Before you press, please wait for the green background to show. Nice try though!").fadeIn();
    highlightBlue.animate({
      height: "327",
    });
  }

});
.average-title {
  text-align: center;
  font-size: 15px;
  color: #ff969f !important;
  margin-top: 30px;
  margin-bottom: 0;
}

.table-stats {
  width: 50%;
  color: white;
  margin-left: auto;
  margin-right: auto;
  margin-top: 50px;
  background-color: #131620;
  text-align: center;
}

.table-stats th {
  border-bottom: 1px solid whitesmoke;
  font-size: 30px;
  width: 50%;
}

th:first-child {
  border-right: 1px solid whitesmoke;
}

td:nth-child(odd) {
  border-right: 1px solid whitesmoke;
}

td {
  border-bottom: 1px solid whitesmoke;
  font-size: 25px;
}

.footer-basic {
  margin-top: 340px;
  background-color: #131620 !important;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
  <title>Reactionz</title>
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="assets/css/Footer-Basic.css">
  <link rel="stylesheet" href="assets/css/Highlight-Blue.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
  <link rel="stylesheet" href="assets/css/Navigation-Clean.css">
  <link rel="stylesheet" href="assets/css/styles.css">
</head>

<body style="background-color: #272E42;">
  <nav class="navbar navbar-light navbar-expand-md navigation-clean" style="background-color: #272e42;">
    <div class="container"><a class="navbar-brand" href="#" style="color: #ff969f;font-size: 20px;">Reactionz</a><button data-toggle="collapse" class="navbar-toggler" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="navbar-toggler-icon"></span></button>
      <div class="collapse navbar-collapse" id="navcol-1">
        <ul class="nav navbar-nav ml-auto">
          <li class="nav-item" role="presentation"><a class="nav-link active" href="#">Home</a></li>
          <li class="nav-item" role="presentation"><a class="nav-link" href="#">About</a></li>
        </ul>
      </div>
    </div>
  </nav>
  <div class="highlight-blue" style="background-color: #131620;">
    <div class="container">
      <div class="intro">
        <h2 class="text-center title-info">How fast do you react?</h2>
        <p class="text-center">Measure your ability to react. CS: GO professionals have an average score of 150ms and the average human fall between 200-250ms.<br><br></p>
      </div>
      <div data-bs-hover-animate="tada" class="buttons"><a class="btn btn-primary wobble animated startSession" role="button" href="#" style="background-color: #ff969f;">React</a></div>
      <p class="average-title">Your average: <span id="average"></span><span id="totalTries"></span></p>
    </div>
  </div>

  <table class="table-stats">
    <tr>
      <th>Time (ms)</th>
      <th>Try</th>
    </tr>
  </table>
  <div class="footer-basic" style="background-color: #272e42;filter: blur(0px) grayscale(0%);">
    <footer>
      <ul class="list-inline">
        <li class="list-inline-item"><a href="#" style="filter: brightness(200%) contrast(0%);">Home</a></li>
        <li class="list-inline-item"></li>
        <li class="list-inline-item"><a href="#" style="filter: blur(0px) brightness(200%) contrast(0%) grayscale(0%);">About</a></li>
        <li class="list-inline-item"></li>
        <li class="list-inline-item"><a href="#" style="filter: brightness(200%) contrast(0%);">Privacy Policy</a></li>
      </ul>
      <p class="copyright">Reactionz © 2019</p>
    </footer>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="assets/bootstrap/js/bootstrap.min.js"></script>
  <script src="assets/js/bs-animation.js"></script>
  <script src="assets/js/script.js"></script>
</body>

</html>