I have read the setTimeout and setinterval functions in many documents about JavaScript. They always think that their functions are completely the same-that is, how long will they be executed, so the setTimeout function has always been used, and the setinterval function has never been used in your own code. In fact, why don't you go further and think about it? If the functions are the same, why is there rationality.
So far, I am used to expressing doubts about the consistency of the two functions. I just suddenly realized that I had to Google them online. There was a difference. First of all, we can understand the two words as follows:
Timeout
Interval: interval, distance, off-screen, interval
The time specified by the setTimeout function table they represent is the time to execute a specified function. At this time, its mission is to complete and only be executed once. The setinterval function executes the specified function at a specified time. If it is not cleared, it will be executed countless times. The setinterval function acts more like the timer control in many programming languages.
The clearing counter functions are cleartimeout and clearinterval. The functions are described as follows:
VaRTimer1 = setTimeout ("foo", 1000 );// Set the foo function to be executed once in 1000 milliseconds
.........// Do something
Cleartimeout (timer1 );// If the program is executed here, when the count starts with setTimeout, 1000 milliseconds fail,
// After cleartimeout, foo cannot be executed
// IF 1000 milliseconds have passed and foo has been triggered for execution, it makes no sense.
VaRTimer2 = setinterval ("foo", 1000 );// Set to execute Foo once every 1000 milliseconds from the current time.
.........// Do something
Clearinterval (timer2 );// Foo will not be triggered later
So such a detail is ignored, and setTimeout + recursion has been used for a long time to simulate setinterval behavior. The following code:
FunctionFoo (){
.......// Do something
SetTimeout ("foo", 1000 );
}
Does the above Code look the same as setinterval? It just seems that there are three lines of code, and it doesn't seem to be much complicated. But why don't we use something simple?