Home > Web Front-end > JS Tutorial > Detailed explanation of how to use JavaScript SetInterval and setTimeout_Basic knowledge

Detailed explanation of how to use JavaScript SetInterval and setTimeout_Basic knowledge

WBOY
Release: 2016-05-16 17:15:01
Original
1311 people have browsed it

The syntax of setTimeout and setInterval are the same. They all have two parameters, one is the code string to be executed, and the other is the time interval in milliseconds after which the code will be executed.
However, there is a difference between the two functions. After executing the code once, setInterval will automatically execute the code repeatedly after a fixed time interval, while setTimeout only executes that code once.
Difference:
window.setTimeout("function",time);//Set a timeout object, executed only once, no cycle
window.setInterval("function",time);//Set a timeout object Timeout object, period = 'Interaction time'
Stop timing:
window.clearTimeout(object) Clear the setTimeout object
window.clearInterval(Object) Clear the setInterval object

Copy code The code is as follows:

PerRefresh();

function PerRefresh() {
var today = new Date();
alert("The time is: " today.toString());
setTimeout("showTime()", 5000);
}

Once this function PerReflesh is called, the time will be displayed every 5 seconds
Copy code Code As follows:

setInterval("PerRefresh()", 5000);

function PerRefresh() {
var today = new Date();
alert(" The time is: " today.toString());
}

And setInterval is not bound by the function it calls. It simply executes it repeatedly at a certain time. that function.
As long as the setInterval("PerRefresh()", 5000) function is called, the PerRefresh function will be executed every 5 seconds.
If you need to perform an action accurately after every fixed time interval, then it is best to use setInterval. If you do not want to cause mutual interference due to continuous calls, especially each function call requires heavy calculations. and long processing time, then it's better to use setTimeout.
setInterval continues to execute the specified code until clearInterval is called to clear the timer object.
setTimeout executes the specified code once and uses clearTimeout to clear the timer object.
Both setInterval and setTimeout return the timer object identifier, which is used for clearInterval and clearTimeout. call
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template