[자바 스크립트] clearInterval ()이 JavaScript로 시계 타이머에서 작동하지 않습니다.
타이머 시작 및 중지를 수정하는 한 가지 방법은 HEAD 태그 사이에서 javascript를 이동하여 html이로드 될 때 함수가 선언되도록하는 것입니다. 나는이 일을했다 :
<html>
<head>
<title>Stuff</title>
<script >
var clock09 = window.setInterval(myTimer09, 1000);
.... your code
</script>
</head>
<body>
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
</body>
</html>
-------------------문제:
이는 기본 로드 유형 이 자바 스크립트 코드를 래핑 하는 onLoad 로 설정 되어 window.onload = function() {}
있으므로 함수의 범위가 함수로 제한되고 onload
외부에서 사용할 수 없었기 때문입니다.
해결책:
Fiddle의 Javascript 섹션에서 Javascript 설정을 클릭하고 No wrap-in body로 변경 하면 body
태그에 Javascript 코드가 배치되므로 작동합니다 .
추가 참고 :
코드는 StackOverflow 스 니펫을 통해서도 작동합니다.
/*My Problem*/
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
/*W3S Problem*/
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML =
d.toLocaleTimeString();
}
<!-- My Problem -->
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
<hr>
<hr>
<!-- W3S Problem -->
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
추천
우려의 분리
외부 파일에서 자바 스크립트 코드를 이동하고 나중에 script
태그를 사용하여 HTML에 포함하는 것이 좋습니다 . 예를 들어 코드를 app.js
옮긴 다음 HTML 에 다음과 같이 포함합니다.
<!-- make sure the path here is relative to the current HTML -->
<script src="./app.js"></script>
-------------------myTimer09 함수에서 새 날짜 변수를 선언하고 있으므로 호출 될 때마다 현재 시간이 표시됩니다. 함수 외부에서 시간을 선언 한 다음 함수에 전달해야합니다. 타이머를 중지 할 때 해당 값으로 다시 시작할 수 있도록 시간 값을 저장해야합니다.
-------------------이것은 JSFiddle의 문제인 것 같습니다.
onclick 핸들러는 실제로 정의되지 않은 window.toggle10을 찾고 있습니다 (콘솔에서 오류 확인). 이것은 다른 사람들이 JSFiddle에서 본 것 같습니다.
코드를 JSbin에 C & P 처리 했으며 설명 된대로 작동합니다 !
출처
https://stackoverflow.com/questions/39940187