Instance code for timers in JavaScript

Source: Internet
Author: User
Tags setinterval

1. Set Timer

Syntax: setinterval (function, time)

Attention:

function cannot be written with parentheses

SetInterval (fn,1000)//correct
SetInterval (FN (), 1000)//Error

The minimum time setting is not less than 14ms

2. Clear Timer

Syntax: Clearinterval (the name of the timer cleared)

3. Case study

JS part

Window.onload =function () {
Vartimer =null;
Varnum = 0;
Vari = 0;
vararr=[' red ', ' #FF9D0C ', ' #DBFF0D ', ' #3BFF0D ', ' #0DFFA2 ', ' #0DE8FF ', ' #0D52FF ', ' #210DFF ', ' #930DFF ', ' #FF0DB4 ']
Varstart = document.getElementById (' start ');
Varstop = document.getElementById (' Stop ');
Varprizedraw = 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

<divid= "Prizedraw" ></div>
<inputtype= "button" value= "Starting" id= "Start" >
<inputtype= "button" value= "Pause" id= "Stop" >

Code Analysis:

Note that when running the timer to clear the timer first, otherwise, if the timer has been clicked, the timer will run multiple, stop also stop;

Clearinterval () can accept the cleared value of NULL;

An application that stores content in an array.

Original link: http://www.cnblogs.com/huyuzhu/p/6200840.html

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.