如何使用按钮单击停止此操作
function MakeCounter(){
var count = 0;
setInterval (countIt, 1000)
function countIt(){
count++;
document.getElementById('demo').innerHTML = count; // result div
}
}
MakeCounter();
答案 0 :(得分:1)
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
clearInterval(myVar);
}
答案 1 :(得分:1)
为Global
声明一些setInterval
变量,然后点击clearInterval(start)
演示片段
var start ;
function MakeCounter(){
var count = 0;
start = setInterval (countIt, 1000)
function countIt(){
count++;
document.getElementById('demo').innerHTML = count; // result div
}
}
MakeCounter();
<p id="demo"></p>
<button onclick="clearInterval(start)">stop</button>
答案 2 :(得分:1)
您可以在函数内部创建按钮,并添加一个用于停止间隔的evelt侦听器。
function MakeCounter() {
function countIt() {
count++;
document.getElementById('demo').innerHTML = count;
}
var count = 0,
interval = setInterval(countIt, 1000),
button = document.createElement('button');
button.appendChild(document.createTextNode('stop'));
button.id = 'stop';
document.body.appendChild(button);
document.getElementById('stop').addEventListener('click', function () {
clearInterval(interval);
}, false);
}
MakeCounter();
&#13;
<div id="demo">0</div>
&#13;