2017-04-17 123 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); 
}