The difference between settimeout and setinterval in JS

Source: Internet
Author: User

Can often be used to refresh an expression.

Example 1

The code is as follows Copy Code

<div id= "a" ></div>
<div id= "B" ></div>
<script type= "Text/javascript" >
SetTimeout ("document.getElementById (' a"). Innerhtml=new Date (). getseconds (); ", 1000);
SetInterval ("document.getElementById (' B '). Innerhtml=new Date (). getseconds ();", 1000);
</script>

SetInterval () case

The code is as follows Copy Code

var leftseconds = 10;
var intervalid;
$ (function () {
$ ("#btnReg"). attr ("Disabled", true);
Intervalid = SetInterval ("Countdown ()", 1000);
});
function Countdown () {
if (Leftseconds <=0) {
$ ("#btnReg"). Val ("submit");
$ ("#btnReg"). attr ("disabled", false);
Clearinterval (Intervalid);
Return
}else{
leftseconds--;
$ ("#btnReg"). Val ("Please read carefully" + Leftseconds + "seconds");
}
}

SetTimeout ()


settimeout (function () {Alert &quot; Hello world&quot;);},1000)

A delay of 1 seconds after execution to this sentence pops up the alert window. So look at this paragraph again:

The code is as follows Copy Code

function A () {

settimeout (function () {alert (1)},0);

Alert (2);

}

A ();

Difference Summary

Using setinterval and setting the delay function settimeout very similar.
SetTimeout is used to delay a period of time and then perform an operation.
SetTimeout ("function", time) sets a timeout object
SetInterval ("function", time)//Set a timeout object

SetInterval for automatic repetition, settimeout will not repeat.
Cleartimeout (object) clears the SetTimeout object that has been set
Clearinterval (object) clears the SetInterval object that has been set

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.