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