<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>clearIntervals()一次關閉全部定時器</title>
</head>
<body>
<div>下面有三個定時器 以不同的時間間隔輸出不一樣內容</div><br><br>
<input type='button' value='輸出「liu」 初始一秒4次' >
<input type="button" value="輸出「jin」 初始一秒2次">
<input type="button" value="輸出「yu」 初始一秒1次">
<button id='clear' style='margin-left:50px;'>清除全部定時器</button>
<div id="div1"></div>
<script type="text/javascript">
var oDiv = document.getElementById('div1');
var aInput = document.getElementsByTagName('input');
var oBtn = document.getElementById('clear');
var arr = [];
var txt = '';
//每次生成的定時器都單獨有一個數組裏的位置,避免了衝突
aInput[0].onclick=function(){
arr.push(setInterval(liu, 250));
}
aInput[1].onclick=function(){
arr.push(setInterval(jin, 500));
}
aInput[2].onclick=function(){
arr.push(setInterval(yu, 1000));
}
//調用自定義函數 用一個for循環 關閉數組中存儲的全部定時器;
oBtn.onclick=function(){
clearIntervals(arr);
}
function liu(){
txt = txt.concat(' Liu')
oDiv.innerHTML=txt;
return txt;
}
function jin(){
txt = txt.concat(' Jin')
oDiv.innerHTML=txt;
return txt;
}
function yu(){
txt = txt.concat(' Yu')
oDiv.innerHTML=txt;
return txt;
}
//原理 用一個數組來保存全部定時器的id
function clearIntervals(array){
for (var i = array.length - 1; i >= 0; i--) {
// if (typeof array[i] !== 'undefined') {
clearInterval(array[i]);
// };
};
}
</script>
</body>
</html>javascript