Usage of setTimeout () in JS _ javascript skills

Source: Internet
Author: User
Tags modulus custom name
SetTimeout () is the method of window, but we all skip the top-level Object Name of window. This is used to set a time. When the time is reached, a specified method will be executed.
  1. SetTimeout
    1. Example of setTimeout syntax
    2. Use setTimeout to execute the function
    3. SetTimeout for repeated execution
    4. Set the condition to stop setTimeout
    5. Scoring and counter in seconds
  2. ClearTimeout
  3. Set flag

1. SetTimeOut ()

1.1 SetTimeOut () syntax example

1.2 use SetTimeOut () to execute the Function

1.3 SetTimeOut () syntax example

1.4 set the condition to stop SetTimeOut ()

1.5 scoring and second counter

2. ClearTimeout ()

3. Set Flag

10.1 setTimeout ()

  SetTimeout ()Is the method of the window, but we all omitted the top-level Object Name of the window, which is used to set a time. When the time is reached, a specified method will be executed. Let's take a look at the next simple example. This example is for demonstration purposes only.SetTimeout ().

1. Example of setTimeout () syntax

Exercise-69 alert () waiting for three seconds ()

When talking about the alert dialog box in Chapter 3rd, it is usually called by a button. In this exercise, you will see that an alert dialog box automatically appears three seconds after the web page is opened.

1.Open the demo disk in the browserTimeout1.htm:


Demonstration webpage



Please wait for three seconds!

Script
SetTimeout ("alert ('
Sorry, you have to wait.')",3000)
Script

2. Check that an alert dialog box appears three seconds after the web page is enabled.

  SetTimeout ()Is to set a specified waiting time (unit: 1‰ seconds, millisecond), when the time is reached, the browser will execute a specified method or function, with the following syntax:

This example is set to wait 3 seconds (3000 milliseconds), and the browser will executeAlert ()This method.

2. use setTimeout () to execute the function

  SetTimeout ()It is usually used with the function. The following is an example of a complex exercise.

Exercise-automatically disappears text in the 70 Status column

InExercise-20You have seen how to use the button to display text in the Status column and then use the button to remove text. In this exercise, you can see how to use the button to display text in the Status column, the text will automatically disappear in three seconds.

1. Open timeout2.htm in the demo disk with a browser. This file contains the following content:


Demonstration webpage


Script
Function
ClearWord()
{Window. status = ""}
Script


2.Click the button, You should see the word "Hello" in the Status column. After three seconds, the word will disappear.

1. Set a nameClearWord ()Is defined as follows:

Window. status = ""

This is the text used to remove the Status column (seeExercise-20In the browser.ClearWord()The text in the Status column is eliminated.

2. This button sets to start the following two tasks, separated by commas (,). the browser will execute these two tasks in sequence:

OnClick = "window. status ='Hello', SetTimeout ('ClearWord()',3000)"

3. This timeSetTimeout ()The following settings are available:

This is set to be executed in 3 seconds (3000 milliseconds ).ClearWord()This function.

In Chapter 2nd, you have seen how to enable a sub-window automatically when the parent window is enabled. If the viewer does not close this sub-window, this sub-window will be enabled all the way. After reading the above exercises, Please design a Web page that will enable the Sub-window. The sub-window will be automatically closed two seconds after it is enabled.

3. setTimeout () for continuous re-execution ()

  SetTimeout ()The preset is only executed once, but we can use a loop To MakeSetTimeout ()Once you start yourself again, it will lead to the secondSetTimeout ()Execute, the second starts the third, so the loop goes down, thisSetTimeout ()It will be executed continuously.

Exercise-71 automatically add 1 function per second

Here you can see how to useSetTimeout ()Increase the value of the text box by 1 per second. Of course, you can set another increasing speed. For example, increase the value by 5 every five seconds or increase the value by 1 every five seconds.

1. Enable timeout3.htm in the demo disk in the browser. This file contains the following content:


Script
X =
0
Function
CountSecond()
{X = x + 1
Document.Fm.
DisplayBox. Value =X
SetTimeout ("
CountSecond()",1000)
}
Script






Script
CountSecond()
Script

2. After the web page is turned on, please pay attention to the numeric transformation in the text box.

3.Please change the hard drive, such as x = x + 5, or change the wait time to 5000 to see how it works..

1. This webpage has two scripts. The first one is to set CountSecond()The second function is to start the function after the webpage is fully loaded.

2. Pay attention to the following settings:

FunctionCountSecond()
{
X=X+ 1
Document.
Fm.DisplayBox. Value = x
SetTimeout ("
CountSecond()",1000)
}

WhenCountSecond()After it is started, it startsSetTimeout ()This method is started again in one second.CountSecond(),CountSecond ()Start again after startupSetTimeout ()So the result isCountSecond ()Run the command once per second.

3. in JavaScript, we use the method described here to execute some items continuously. One of the purposes is to display the rotation time, and the other is to set the running text. The following sections will show examples.

Set the time using the above method,SetTimeout ()Although it is set to one second, the browser still has two other functions to execute, so the cycle time is a little more than one second, for example, one minute may only have 58 cycles.

4. Set the condition to stop setTimeout ()

  SetTimeout ()When the circle starts, it will continue to repeat. In the previous exercise, you can see that the number in the text box is continuously beating, but we have a way to stop when the number jumps to a value, one method is to useIf... elseSet a condition to continue execution if it is TRUE.SetTimeout ()If it is FALSE, it is stopped.

For example, if you want to jump to counter 20 of the previous exercise, you can stop the related function by making the following changes.

FunctionCountSecond()
{If (
X<20)
{
X=X+1
Document.
DisplaySec.DisplayBox. Value =X
SetTimeout ("
CountSecond() ", 1000)
}
}

5. scoring and counter in seconds

In the previous exercises, I believe you have learned how to use them.SetTimeout ()For more information, see the following example.

Exercise-72-hour counter

In this exercise, you need to set two text boxes, one to display for minutes and the other to display for seconds. After the web page is turned on, it will automatically time in these two text boxes.

1.Open the demo disk in the browserTimeout4.htm:


Script
X= 0
Y=-1

FunctionCountMin()
{Y=Y+ 1
Document.DisplayMin.DisplayBox. Value =Y
SetTimeout ("CountMin() ", 60000)
}

FunctionCountSec()
{
X=X+1
  Z=
X%60
Document.
DisplaySec.DisplayBox. Value =Z
SetTimeout ("
CountSec()",1000)
}
Script










Your connection time on this webpage is: Minute Seconds.


Script
CountMin ()
CountSec ()
Script

2. Please pay attention to the number transformation in the two text boxes.

1. This webpage has two functions, one for minutes and the other for seconds. Here, I just demonstrateSetTimeout ()Because there are other more streamlined timer writing methods.(Note: the timing is not accurate .)

2. Pay attention to the second function:

FunctionCountSec()
{
X=X+1
  Z
=X%60
Document.
DisplaySec.DisplayBox. Value =Z
SetTimeout ("
CountSec()",1000)

}

The%The symbol is modulus (remainder), for example Z=X%60 indicates first lineX/60,Returns the remainderZThis variable, for example, 82 seconds, modulus is 22, so the text box will display 22 instead of 82.

3. If you want to add 0 in front of a unit number, such as 01, 02, and 03, use the following method:

FunctionCountSec()
{
X =X+1
  Z=
X%60
If (
Z<10){Z="0"+Z}
Document.
DisplaySec.DisplayBox. Value =Z
SetTimeout ("
CountSec()",1000)
}

10.2 clearTimeout ()

In the previous section, you have seen how to useSetTimeout ()To enable the browser to continuously execute a function.SetTimeout ()We started loop work. To stop it, we can useClearTimeout ()This method.

ClearTimout ()Syntax:ClearTimeout (TimeoutID)

To useClearTimeout (), We setSetTimeout ()To give thisSetTimout ()A name, which isTimeoutIDWhen we call the stop, we use thisTimeoutIDThis is a custom name, but many programmers useTimeoutID.

In the following example, the author sets twoTimeoutID, Respectively namedMeter1AndMeter2, As follows:

TimeoutID
Bytes
Meter1= SetTimeout ("Count1()",1000)
Meter2= SetTimeout ("Count2()",1000)

Use thisMeter1AndMeter2TheseTimeoutIDName.ClearTimeout ()You can specifySetTimeout ()Valid, not disturbing the otherSetTimeout ().

Exercise-73 stopable setTimeout ()

This exercise usesExercise-71But two changes were made: (1) There are twoSetTimeout (), (2) There are two buttons to stop the twoSetTimout ().

1.Open the demo disk in the browserClear.htm:


Script
X=0
Y=0

FunctionCount1()
{
X=X+1
Document.
Display1.Box1. Value =X
  Meter1
= SetTimeout ("Count1()",1000)
}

FunctionCount2()
{
Y=Y+1
Document.
Display2.Box2. Value =Y
  Meter2
= SetTimeout ("Count2()",1000)
}
Script








Script
Count1()
Count2()
Script

2. Pay attention to the two text boxes on the webpage and the numbers changed in the text box. There are two buttons next to each text box,Please try the response of two buttons.

3.Please press the [Continue timing] button multiple times in a row, Pay attention to the increase in the number of beats, the reason is that the function is started once every time, each function makes the value beat, for example, to start the same function four times, it will jump four times a second. (Please refer to the next section)

10.3 Set flag

In the previous exercise, we used a button to start a function. Every time you press it, the function is started once. See the following example.

Exercise-74 effect-heavy explain setTimeout ()

In practiceExercise-73Simplified: there is only one timer. I want to demonstrate that every time I press [Continue timing], it will startCount()This function once.

1.Open the demo disk in the browserFlag1.htm:


Script
X=0
Function
Count()
{
X=X+1
Document.
Display.Box. Value =X
  TimeoutID
= SetTimeout ("Count()",1000)
}
Script



Script
Count()
Script

2. When the webpage is turned on, you should see the number in the text box beating,Please [Continue timing] four times, Note that this will speed up the number beating because multiple related functions are enabled, and each function will change the number.

3. After four [Continue timing] buttons,Please press the [stop timing] button, You will find that you have to press five times to stop the number.

When writing a program, we often need to watch out for some special actions. For example, if the user presses the [Continue timing] button twice, this timer will be inaccurate. Is there a way to invalidate a button once? This will not produce a duplicate effect.

The author uses this example (there are multiple examples later) to explain the concept of a set flag in the program. flag is a recognition. Generally, this can be 0 or 1 (on or off, or any two names or numbers of your choice), but it can also be 2, 3, 4 or a larger number, the following settings are available in this example:

1. When the program is enabled Flag=0.

2. WhenCounter ()During executionFlagTo 1.

3. In the response to the [Continue timing] button, checkFlagIf it is 0 or 1, it will take effect if it is 0, and if it is 1, there will be no response.

4. Use this flag,Count()After this function is enabled, the [Continue timing] button does not work.

The flag here is a variable, which can be named at will. We use the flag to name this variable because it benefits a flag to be erected (flag is on ), the flag is off.

Exercise-function 75 can be enabled only once

This exercise adds one more flag to the previous exercise so that only one count () function can be performed at a time.

1.Open the demo disk in the browserFlag2.htm:


Script
X=0
Flag=0
Function
Count()
{
X=X+1
Document.
Display.Box. Value =X
  TimeoutID
= SetTimeout ("Count()",1000)
  Flag
=1
}

FunctionRestart()
{If (
Flag=0)
{
Count()}
}
Script



Script
Count()
Script


2. on the webpage, you should see three buttons and numbers in the text box beating.

3.Please press the [Show flag] button, The flag should be 1 on the box.

4.Please press the [stop timing] button and the number stops beating. Please press the [Show flag] buttonThe flag is 0 on the box.

5.Please press the [Continue timing] button multiple times. It will not speed up when you see the number. Please press the [Show flag] button. If yes, the flag is changed to 1.

1. There is a sentence in line 3 of this webpage:Flag=0. This is the setting.FlagThis variable and the initial value are set to 0. You can also set the initial value to 1, and then perform the corresponding 0 and 1 reconciliation.

2.Count()The last sentence of this function is Flag=1, so startCount()After,FlagIt will change to 1.

3. The [Continue timing] button is used to startRestart()This function has the following settings:

FunctionRestart()
{If (
Flag=0)
{
Count()}
}

If statement checkFlagWhether it is equal to 0. If it is 0, it is started.Count()If it is 1 (not 0), there is no response. Use this method. IfCount()In progress, the [Continue timing] button does not work.

TheFlag=The values set to 1, 2, or 3 are the same, as long as they are not 0, so the two relative flags, it seems to be "0" and "1", actually "0" and "non-zero" (non-0 ).

4. The [stop timing] button has the following settings:

OnClick = "clearTimeout (TimeoutID);Flag=0"

This is stoppedSetTimeout ()OperationFlagReturns 0, which causesRestart()This function can be restarted. Count().

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.