Home > Web Front-end > JS Tutorial > body text

How to use JavaScript setTimeout and setInterval Explanation_javascript tips

WBOY
Release: 2016-05-16 18:31:22
Original
1396 people have browsed it

The difference is that setInterval will execute the code every specified time period, which is repetitive. And setTimeout will only be executed once after being called.
The following is a deep understanding of the two functions through the establishment of the function and the automatic deletion of the function;
1. The establishment of the function
The establishment of setTimeOut:

Copy code The code is as follows:

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

The showtime function will be executed only five seconds after calling the function
Establishment of setInterval
Copy code The code is as follows:

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

Summary: It seems that the results of the two functions are similar, but in fact, otherwise the second function will repeatedly report the time until the web page is closed.
Elimination of two functions:
The elimination of setTimeout uses the
clearTimeout() function; call example:
Copy code The code is as follows:

var timeoutProcess = setTimeout("alert('GOAL!')", 3000);
var stopGoalLink = document.getElementById("stopGoalLink");
attachEventListener(stopGoalLink, "click", stopGoal, false);//Add the event function, the parameters are (target; event; function called; whether to bubble)
function stopGoal()
{
clearTimeout(timeoutProcess);
}

Elimination of setInterval
Copy code The code is as follows:

var timeoutProcess = setTimeout("alert('GOAL!')", 3000);
var stopGoalLink = document.getElementById("stopGoalLink");
attachEventListener(stopGoalLink, " click", stopGoal, false);//Add the event function, the parameters are (target; event; function called; whether to bubble)
function stopGoal()
{
clearInterval(timeoutProcess);
}
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