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

The difference between setTimeout() and setInterval() timers in JavaScript

藏色散人
Release: 2019-04-09 10:15:00
Original
5044 people have browsed it

This article will introduce to you the differences in the use of setTimeout() and setInterval() timers in JavaScript. (Recommended: "javascript tutorial")

setTimeout() method

setTimeout() method is waiting for the specified Execute a function after the number of milliseconds.

Syntax:

window.setTimeout(function, milliseconds);
function : 第一个参数是要执行的函数
milliseconds : 表示执行前的毫秒数.
Copy after login

For example, we want a prompt box to pop up 2 seconds after the user presses the "Click me!" button.

The javascript code is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>

<button onclick="setTimeout(gfg, 2000);">点击我!</button>

<script>
    function gfg()
    {
        alert(&#39;欢迎来到PHP中文网!&#39;);
    }
</script>

</body>
</html>
Copy after login

Output:

Once the user presses the "Press Me" button, then after a pause of 2 seconds, a box will pop up.

The difference between setTimeout() and setInterval() timers in JavaScript

The difference between setTimeout() and setInterval() timers in JavaScript

##setInterval() method

setInterval()method Repeat a given function at every given time interval.

Syntax:

window.setInterval(function, milliseconds);

function : 第一个参数是要执行的函数
milliseconds :表示每次执行之间的时间间隔的长度。
Copy after login

The code example is as follows:


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>

<p>我会说“你好”很多次!</p>

<p id="GFG"></p>

<script>
    var myVar = setInterval(myTimer, 1000);

    function myTimer()
    {

        document.getElementById("GFG").innerHTML += "<p>你好</p>";
    }
</script>

</body>
</html>
Copy after login
A new "Hello" message will be displayed every second.

The difference between setTimeout() and setInterval() timers in JavaScript

Then:

The difference between setTimeout() and setInterval() timers in JavaScript

This article is about the two timers setTimeout() and setInterval() in JavaScript The differences are introduced, I hope it will be helpful to friends in need!

The above is the detailed content of The difference between setTimeout() and setInterval() timers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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