2. 清除定时器
语法:clearInterval(所清除的定时器名称)
3. 实例探究
js部分
window.onload = function() { var timer = null; var num = 0; var i = 0; var arr=['red','#FF9D0C','#DBFF0D','#3BFF0D','#0DFFA2','#0DE8FF','#0D52FF','#210DFF','#930DFF','#FF0DB4'] var start = document.getElementById('start'); var stop = document.getElementById('stop'); var prizeDraw = document.getElementById('prizeDraw'); start.onclick = function() { clearInterval(timer); timer = setInterval(function(){ num = Math.floor(Math.random()*100+1); prizeDraw.style.backgroundColor = arr[i]; i++; if (i==9) { i = 0; }; prizeDraw.innerHTML = num; },100); } stop.onclick = function() { clearInterval(timer); } }
css部分
#prizeDraw { width: 100px; height: 100px; background: rgba(255,68,253,0.5); font-size: 30px; text-align: center; line-height: 100px; }
html部分
<div></div> <input type="button" value="开始"> <input type="button" value="暂停">
代码分析:
注意在运行定时器的时候要先清除定时器,不然如果一直点击运行定时器,定时器就会运行多个,点停也停不下来;
clearInterval()可以接受清除的值为null;
将内容存放在数组中的应用。