Use the setTimeout () function to implement the delay execution of the function code

xiaoxiao2021-04-06  278

In some cases, we may want some of the code in the program to execute it first, then stay again, then perform other program code, but JS writes in order, even a large loop (such as While (i <100000)) will also be completed soon, and it will not be accurately controlled because the execution speed of the loop is dependent on the user's CPU, so we must use the clock to set, and then there is a function setTimeout function in JS, used for Set how long the specified code is performed for a long time. Such as setTimeout ("A ()", 1000), refers to the function a () after 1 second, using the settimeout function we can easily complete the above problem, we can write a () clock to delay the executed code write A function such as a B1 () clock, then the end of the original function on the end of SetTimeout ("B1 ()", 3000), then the program in the B1 () function is executed after 3 seconds. This enables the function of delaying the formulation of the 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

>

HEAD

>

<

Body

>

<

Div

id

= "a"

>

Div

>

<

Script

Type

= "Text / JavaScript"

>

FUNCTION

A () {document.getlementByid (

"

a

"

) .innerhtml

=

"

AAA

"

; Document.getlementByid (

"

a

"

) .innerhtml

=

"

Wait 6 Seconds Later

"

Settimeout

"

b ()

"

,

6000

}

FUNCTION

b () {document.getlementByid (

"

a

"

) .innerhtml

=

"

CCCCC

"

} a ();

Script

>

Body

>

HTML

>

转载请注明原文地址:https://www.9cbs.com/read-132328.html

New Post(0)