Проблема с моей функцией clearInterval - PullRequest
0 голосов
/ 29 декабря 2011
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
<!--

function init()
{
  timeDisplay = document.createTextNode ( "" );
  document.getElementById("clock").appendChild ( timeDisplay );
}

function updateClock()
{
  var currentTime = new Date ();

  var currentHours = currentTime.getHours();
  var currentMinutes = currentTime.getMinutes();
  var currentSeconds = currentTime.getSeconds();

  // Adds zeros if required
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

  // Decides whether AM or PM
  var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

  // Convert the hours component to 12-hour format if needed
  currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

  // Convert an hours component of "0" to "12"
  currentHours = ( currentHours == 0 ) ? 12 : currentHours;

  // Creates the display string
  var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

  // Updates the time display
  document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}

// -->
</script>
<link rel="stylesheet" type="text/css" href="week9live.css" />
</head>

<body onload="updateClock(); setInterval('updateClock()', 1000 )">
<h1>A live clock in Javascript</h1>
<div>
  <p>The time according to your pc is </p> <span id="clock">&nbsp;</span>
</div>
</br>
<button type ="button" onclick = "clearInterval('updateClock()')">Stop Clock</button>
<button type="button" onclick="setInterval('updateClock()', 1000)">Start Clock</button>
</body>
</html>

У меня есть много HTML-кода, который я использовал для генерации живых часов. Затем мне было поручено создать две кнопки, одна из которых останавливает часы, а вторая - перезапускает. Моя функция setInterval работает нормально, но я не могу понять, почему функция clearInterval не работает. Есть идеи?

Приветствия

Ответы [ 3 ]

3 голосов
/ 29 декабря 2011

Вам необходимо сохранить значение, которое вернуло из setInterval, и передать , который , в ваш вызов на clearInterval.

var idForClear = setInterval(updateClock, 1000);

, а затем

clearInterval(idForClear);

Это будет намного проще, если вы откажетесь от встроенных обработчиков уровня 0 и сделаете что-то подобное

<button id="stopBtn" type ="button">Stop Clock</button>
<button id="startBtn" type="button">Start Clock</button>

var idForClear;
document.getElementById("startBtn").onclick = function() {
    idForClear = setInterval(updateClock, 1000);
};
document.getElementById("stopBtn").onclick = function() {
    clearInterval(idForClear);
};

Просто убедитесь, что вы поместили этот скрипт в внизу тела вашей страницы, чтобы убедиться, что document.getElementById не вызывается до того, как вы будете готовы.


Также обычно считается злым называть setTimeout или setInterval строкой. Когда вы не в встроенном обработчике, вместо этого

setInterval('updateClock()', 1000);

Вы хотите передать в функцию

setInterval(function() { updateClock(); }, 1000);

Но, конечно же, updateClock - это тоже функция, поэтому вышеприведенный код более шумно эквивалентен

setInterval(updateClock, 1000);
0 голосов
/ 29 декабря 2011

Передать идентификатор setInterval в clearInterval См .: ClearInterval

0 голосов
/ 29 декабря 2011

Функция clearInterval должна получить идентификатор, сгенерированный setInterval. Что-то вроде:

var theid = setInterval('updateClock()', 1000);
clearInterval(theid);
...