Ara Malki
Ara Malki

Reputation: 185

Prevent function to go any further after jQuery click

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>

I am trying to create a reaction-time-test application. The problem I have is that if the user presses to soon on the div, the user should be blocked from the next function to be executed.

My original idea is that if the user presses the div too soon then he should be forced to the tooSoon() function. It's working, but the problem is that the last line is also executed, and I know why, but I don't know how to prevent it.

Is there any other way to go?

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

Upvotes: 0

Views: 133

Answers (2)

shrys
shrys

Reputation: 5960

You can use clearTimeout() when the event occurs before intended time:

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>

Upvotes: 1

remborg
remborg

Reputation: 548

The problem here is because click and setTimeout are asynchronous. You could share a value between them:

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

Upvotes: 1

Related Questions