주어진 코드에서 setInterval()
및 clearInterval()
메서드를 사용하고 있습니다. 여기에 setInterval()
에 대한 두 개의 버튼과 clearInterval()
의 두 개의 버튼이 있습니다. 두 버튼을 모두 클릭하면 clearInterval()
버튼이 작동하지 않습니다.clearInterval()은 어떻게 작동합니까?
HTML :
<div id="a"></div>
<button id='bt1'>start</button>
<button id='bt2'>Stop</button>
<button id='bt3'>Start</button>
<button id='bt4'>Stop</button>
자바 스크립트 :
var Graph = {
graph: null,
start: function (i) {
this.graph = setInterval(function() {
$('#a').html(i++);
}, 1000);
},
stop: function() {
window.clearInterval(this.graph);
}
};
$('#bt1').click(function(){
Graph.start(1);
});
$('#bt2').click(function(){
Graph.stop();
});
$('#bt3').click(function(){
Graph.start(1);
});
$('#bt4').click(function(){
Graph.stop();
});
바이올린 : Fiddle
'start()'메소드에서'setInterval()'호출 전에 다음 코드를 입력하기 만하면됩니다. 이것은 이전 실행중인 타이머를 정지시킵니다 : if (this.graph) {this.stop(); }'자세한 내용은 내 [편집 된 답변] (http://stackoverflow.com/questions/21108579/how-does-clearinterval-works/21108832#21108832)을 참조하십시오. –