Js timer instance sharing, js timer instance

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.