Javascript interval timer (delayed Timer) Learning interval call and delayed call

Source: Internet
Author: User

The setInterval method can be used to call the function cyclically at a specified interval until the clearInterval method cancels the loop.

When the clearInterval method is used to cancel a loop, you must assign a value to the call of the setInterval method, and then the clearInterval method references the variable.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var n = 0;
Function print (){
Document. writeln (n );

If (n = 1000 ){
Window. clearInterval (s );
}
N ++;
}
Var s = window. setInterval (print, 10 );
</Script>

Use setTimeout and clearTimeout to call latency. After the specified delay time, run the specified function only once. ClearTimeout is used in the same way as clearInterval.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function printTime (){
Var time = new Date ();
Var year = time. getFullYear ();
Var month = (time. getMonth () + 1;
Var daynum = time. getDay ();
Var hour = time. getHours ();
Var min = time. getMinutes ();
Var sec = time. getSeconds ();
Var da = time. getDate ();
Var daystr;
Switch (daynum ){
Case 0: daystr = "Sunday ";
Break;
Case 1: daystr = "Monday ";
Break;
Case 2: daystr = "Tuesday ";
Break;
Case 3: daystr = "Wednesday ";
Break;
Case 4: daystr = "Thursday ";
Break;
Case 5: daystr = "Friday ";
Break;
Case 6: daystr = "Saturday ";
Break;
Default: daystr = "";
}
Var str = year + "year" + month + "month" + da + "day" + daystr + "" + hour + ":" + min + ":" + sec;
Document. getElementById ("t"). innerHTML = str;
Window. setTimeout (printtime, 1000 );
}
</Script>

<Body onload = "printTime ()">
<Br/>
<Div id = "t"> </div>
</Body>

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.