Js timer instance sharing, js timer instance
1. Set the timer
Syntax: setInterval (function, time)
Note:
Function writing cannot contain parentheses
SetInterval (fn, 1000) // correct setInterval (fn (), 1000) // Error
The minimum time is not less than 14 ms.
2. Clear the timer
Syntax: clearInterval (the name of the cleared timer)
3. instance Exploration
Js Section
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 Section
#prizeDraw { width: 100px; height: 100px; background: rgba(255,68,253,0.5); font-size: 30px; text-align: center; line-height: 100px; }
Html section
<Div id = "prizeDraw"> </div> <input type = "button" value = "start" id = "start"> <input type = "button" value =" pause "id =" stop ">
Code Analysis:
Note that you must clear the timer before running the timer. Otherwise, if you keep clicking run timer, the timer will run multiple times and the timer will not stop;
ClearInterval () values that can be cleared are null;
Store the content in the array.
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!