2017-04-17 12 views
0

私はプログラムを動かして停止したい。 このプログラムにはボタンが1つしかありません。ボタンはすべてのプログラムです。 ええ、それは超簡単なプログラムです。 プログラムの問題は、ボールが止まらないことです。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:ヌルの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); 
} 
関連する問題