Почему моя кнопка не запускает таймер? - PullRequest
0 голосов
/ 07 сентября 2018

Я нашел очень простой пример Javascript, чтобы узнать, как работают таймеры. Я сравниваю код с нескольких часов, и я не запускаю его. Обновление часов работает, но кнопка не запускает трекер времени.

Где моя ошибка?

Ниже приведен пример кода JS. Часы обновляются периодически в соответствии с определенным setInterval (). Я не могу найти ошибку, которая запускает запуск часов сразу после нажатия кнопки.

$(function() {
  registerClock();
  setTime();
});

var currentdate;
var stopWatchRunning = false;
var startTime;

function registerClock() {
  setInterval(updateClock, 250);
}

function updateClock() {
  setTime();
  setStopWatch();
}



function setTime() {
  currentdate = new Date();
  var datetime = +currentdate.getDate() + "." +
    (currentdate.getMonth() + 1) + "." +
    currentdate.getFullYear() + " " +
    currentdate.getHours() + ":" +
    currentdate.getMinutes() + ":" +
    currentdate.getSeconds();
  $("#time").text(datetime);
}


$("#startstop").click(function() {
  if (stopWatchRunning == false) {
    startTime = new Date();
    stopWatchRunning = true;
  } else {
    stopWatchRunning = false;
  }
});


function setStopWatch() {
  if (stopWatchRunning == false) {
    return;
  }
  var timeElapsed = currentdate - startTime;
  var duration = new Date(timeElapsed);
  var showDuration = duration.getHours() - 1 + ":" +
    duration.getMinutes() + ":" +
    duration.getSeconds();
  $("#tracker").text(showDuration);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/timer_neu.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">Stoppuhr</a>
    </div>
  </div>
</nav>
<div class="row">
  <div class="col-md-5">
    <h1>Uhrzeit</h1>
    <h1 id="time">19:53:00</h1>
  </div>

  <div class="col-md-5">
    <h1>Stoppuhr</h1>
    <h1 id="tracker">00:00:00</h1>
  </div>

  <div class="col-md-2">
    <p><button id="startstop" class="btn btn-default">Start/Stop</button></p>
    <div>
    </div>

1 Ответ

0 голосов
/ 07 сентября 2018

Переместите функцию щелчка $ ("# StartStop") внутри функции готовности документа, как показано ниже

$(function() {
  registerClock();
  setTime();

  $("#startstop").click(function() {
    //alert('change')
  if (stopWatchRunning == false) {
      startTime = new Date();
      stopWatchRunning = true;
    } else {
      stopWatchRunning = false;
    }
  });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...