1

タイマーを作成しましたが、5 秒または 10 秒ごとに何かを行う必要があります。setTimeout または setInterval 関数を使用したくありませんが、このタイマーを使用する場合、秒の値に対処する方法がわかりません。5000 などと書くべきでしょうか?

function display(){
    var endTime = new Date();
    var timeDiff = endTime - startTime;
    timeDiff /= 1000;

    var seconds = Math.round(timeDiff % 60);
    timeDiff = Math.floor(timeDiff / 60);

//showing the seconds passed
    $("#time").text(seconds);
    setTimeout(display,1000);
}

//starts the timer
$("#start").click(function() {
     startTime = new Date();
     setTimeout(display,1000);
});

/confirms it is 5 seconds
if (timeDiff == 5){
    alert('now');
}
4

1 に答える 1

0

あなたのコードは問題ないようです.タイマーで動作している場合、必要な唯一のことは、timeDiffの条件チェックを次の方法で表示関数内に移動することです:

<html>

<head>
  <script src="https://code.jquery.com/jquery-2.2.3.js" integrity="sha256-laXWtGydpwqJ8JA+X9x2miwmaiKhn8tVmOVEigRNtP4=" crossorigin="anonymous"></script>
  <script>
    $(document).ready(function(e) {


      var prevSec = 0,
        totalTime = 0;

      function display() {
        var endTime = new Date();
        var timeDiff = endTime - startTime;
        timeDiff /= 1000;

        var seconds = Math.round(timeDiff % 60);
        timeDiff = Math.floor(timeDiff / 60);

        //showing the seconds passed
        $("#time").text(seconds);
        //confirm it is 5 seconds
        if (seconds - prevSec == 5) {
          prevSec = seconds;
          totalTime = totalTime + 5;
          $("#text2").text("Another round of 5 seconds is over. Total time : " + totalTime + " seconds");
          // Do whatever you want

        }

        setTimeout(display, 1000);
      }

      //starts the timer
      $("#start").click(function() {
        startTime = new Date();
        setTimeout(display, 1000);
      });

    });
  </script>
</head>

<body>
  Time:
  <p id="time"></p>
  <button id="start">start</button>
  <br>
  <br>
  <br>Display Text :
  <p id="text2"></p>
</body>

</html>

于 2016-04-18T19:00:52.363 に答える