Using settimeout () function to implement delay execution of function code __ function

Source: Internet
Author: User

In some cases, we may want some code in the program to execute first, then stay n seconds before executing other program code, but the content that JS writes to sequentially executes once, even if use a big loop (like while (i<100000)) also can finish quickly, And can not precisely control the time, because the speed of the loop is dependent on the user's CPU, so we have to use the clock to set, and then JS has a function settimeout function, to set the timeout for how long to execute the specified code. such as settimeout ("A ()", 1000), means 1 seconds after the execution of function A (),

Using the SetTimeout function we can easily complete the above problem, we can write a () clock to delay the execution of the code written to a function such as B1 () clock, and then the original function at the end of the SetTimeout ("B1 ()", 3000), then B1 () The program ash in the function executes after 3 seconds. This enables the ability to delay the execution of code.

Test code: <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns = "http://www.w3.org/1999/xhtml" Xml:lang = "en" lang = "en" >
< head >
< title ></title >
< BODY >
< div id = "a" ></div >
< script type = "Text/javascript" >
function A () {
document.getElementById ("a"). InnerHTML = "AAA";
document.getElementById ("a"). InnerHTML + = "Wait 6 seconds later";
SetTimeout ("B ()", 6000);
}
Function B () {
document.getElementById ("a"). InnerHTML + = "CCCCC";
}
A ();
</script >
</Body >
</HTML >

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.