2017-04-17 20 views
0

이동 및 정지 프로그램을 만들고 싶습니다. 이 프로그램에는 단 하나의 버튼이 있습니다. 버튼은 모든 프로그램입니다. 예, 아주 간단한 프로그램입니다. 프로그램의 문제는 공이 멈추지 않는다는 것입니다.setInterval을 중지하는 방법? clearInterval이 작동하지 않습니다.

function onSubmit() { 
    var tev = setInterval(move, 500); 
    if (animate == false) { 
    setInterval(move, 500); 
    animate = true; 
    } else { 
    clearInterval(tev); 
    animate = false; 
    } 
} 
<input type="button" onclick="onSubmit();" value="Shoot"/> 

내가 촬영 버튼을 클릭하면 볼이 이동해야되고 싶은 것은, 클릭 다시 중지합니다. 코드를 실행하면 한 번 클릭하면 공이 올바르게 이동합니다. 다시 클릭하십시오, 멈추지 않습니다. 내 문제 야. 공을 멈추는 방법?

답변

1

버튼을 누를 때마다 tev을 재설정하는 것이 문제입니다. 그 값을 함수 밖에서 저장하면 잘 작동합니다.

// Save outside of the function so it will keep it's value 
 
var timeoutID; 
 
document.getElementById('clickMe').addEventListener('click', function() { 
 
    // Notice that I'm not re-assigning timeoutID 
 
    // every time I click the button 
 
    if (timeoutID) { 
 
    console.log('Stopped'); 
 
    clearInterval(timeoutID); 
 
    
 
    // Clear out the ID value so we're ready to start again 
 
    timeoutID = null; 
 
    } else { 
 
    timeoutID = setInterval(function() { 
 
     console.log('Rolling...'); 
 
    }, 500); 
 
    } 
 
});
<button id="clickMe">Start/Stop</button>

+0

내가 당신에게 한 가지 부탁 할 수 있습니까? 이 코드를 복사하고 실행하면 Chrome에서 'Uncaught TypeError : null'속성 'addEventListener'을 읽을 수 없습니다. –

+0

@nuroo 아마도 데모 용으로 추가 한 버튼이 없기 때문일 것입니다. –

0
var moving = false; 
var interval; 

// handle the click 
function handleClick() { 
    // if moving set moving to false, otherwise set it to true 
    moving = moving ? stop() : start(); 
} 

// start the interval that calls move function and set moving to true 
function start() { 
    moving = true; 
    interval = setInterval(function() { 
     move(); 
    }, 500); 
} 

// clear the interval and set moving to false 
function stop() { 
    moving = false; 
    clearInterval(interval); 
}