Summary of JavaScript's setTimeout() usage

Summary of JavaScript's setTimeout() usage

1. Introduction

The setTimeout method of js is very useful, usually used for page refresh, delayed execution, etc. However, many JavaScript novices still don't understand the usage of setTimeout. Although I have been learning and applying javascript for more than two years, I still need to look up information about setTimeout method sometimes. Today I will make a systematic summary of the setTimeout method of js.

2. The difference between setInterval and setTimeout

When talking about setTimeout , it is easy to think of setInterval , because the two usages are similar, but there are differences. Let’s summarize them together today!

3. setTimeout

Definition and Usage: setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds.

Syntax: setTimeout(code,millisec)

Parameters: code (required): The JavaScript code string to be executed after the function is called. millisec (required): The number of milliseconds to wait before executing code.

Tip: setTimeout() executes the code only once. If you want to call it multiple times, use setInterval() or have the code itself call setTimeout() again.

setInterval:

setInterval() method calls a function or evaluates an expression at a specified period (in milliseconds).

setInterval() method will call the function continuously until clearInterval() is called or the window is closed. The ID value setInterval() 返can be used as a parameter to clearInterval() method.

Syntax: setInterval(code,millisec[,"lang"])

Parameters: code . The function to call or the string of code to execute. millisec required. The time interval between periodic execution or calls of code , in milliseconds.

Return value: A value that can be passed to Window.clearInterval() to cancel the periodic execution of code .

the difference:

As can be seen above, the main differences between setTimeout and setinterval are:

setTimeout only runs once, which means that when the set time is up, it triggers the execution of the specified code and ends when it is finished. If you run the same setTimeout command again in the running code, it can run in a loop. (That is, to run in a loop, the function itself needs to call setTimeout() again)

setinterval runs in a loop, that is, it triggers the specified code every time the set time interval is reached. This is a real timer.

setinterval is simple to use, while setTimeout is more flexible. You can exit the loop at any time and can be set to run at irregular time intervals, such as 1 second for the first time, 2 seconds for the second time, and 3 seconds for the third time.

Personally, I prefer to use setTimeout more!

4. Usage of setTimeout

Let's run a case together. First, open Notepad, paste the following code in, and run it to see the effect!

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1> <font color=blue> haorooms blog demonstration page</font> </h1>
<p>Please wait three seconds!</p>

<script>
setTimeout("alert('Sorry, haorooms blog has kept you waiting for a long time')", 3000 )
</script>

</body> 
</html>


The page will pop up a picture frame after staying for three seconds! This case applies the most basic syntax of setTimeout . setTimeout will not be automatically repeated!

setTimeout can also execute function and can execute them repeatedly!

Let’s do another case together:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
var x = 0
function countSecond()
{
   x = x+1
 document.haorooms.haoroomsinput.value=x
 setTimeout("countSecond()", 1000)
}
</script>
</head>
<html>
<body>

<form name="haorooms">
   <input type="text" name="haoroomsinput"value="0" size=4 >
</form>

<script>
countSecond()
</script>

</body> </html>

We can see that the number in the input text box is increasing second by second! Therefore, setTimeout can also make time jumps in web pages!

Without examples, learning will not be fast. Let's do another example to calculate your stay time on a certain page of haorooms :

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
x=0
y=-1
function countMin()
{ y=y+1
 document.displayMin.displayBox.value=y
 setTimeout("countMin()",60000)
}
function countSec()
{ x = x + 1
 z = x % 60
 document.displaySec.displayBox.value=z
 setTimeout("countSec()", 1000)
}
</script> </head>
<body>
<table> <tr valign=top> <td> Your stay time in haorooms blog is: </td>
<td> 
<form name=displayMin>
   <input type=text name=displayBox value=0 size=4 >
</form> 
</td>
<td> points</td>
<td> 
<form name=displaySec> </td>
<td> <input type=text name=displayBox value=0 size=4 >
</form>
 </td>
<td> seconds. </td> </tr>
 </table>
<script>
countMin()
countSec()
</script>
</body>
</html>


How about it? Through the above examples, I believe you have understood the usage of setTimeout() !

5. clearTimeout()

Let's take a look at clearTimeout( ) .

clearTimout() has the following syntax:

clearTimeout(timeoutID)

To use clearTimeout( ) , when we set setTimeout( ) , we need to give this setTimout( ) a name, which is timeoutID . When we stop it, we use this timeoutID to stop it. This is a custom name, but many people name it timeoutID .

In the following example, two timeoutID are set, named meter1 and meter2 respectively.

as follows:

timeoutID ↓ meter1 = setTimeout(“count1( )”, 1000) meter2 = setTimeout(“count2( )”, 1000)

By using the timeoutID names meter1 and meter2, when setting clearTimeout( ) , you can specify which setTimeout( ) is effective, without interfering with the operation of another setTimeout().

Please see the example of clearTimeout() below;

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script>
x = 0
y = 0
function count1()
{ x = x + 1
 document.display1.box1.value = x
 meter1=setTimeout("count1()", 1000)
}
function count2()
{ y = y + 1
 document.display2.box2.value = y
 meter2 = setTimeout("count2()", 1000)
}
</script> </head>
<body> 
<p> </br>
<form name="display1">
    <input type="text" name="box1" value="0" size=4 >
    <input type=button value="Stop timing" onClick="clearTimeout(meter1) " >
    <input type=button value="Continue timing" onClick="count1()" >
</form>
<p>
<form name="display2">
    <input type="text" name="box2" value="0" size=4 >
    <input type=button value="Stop timing" onClick="clearTimeout(meter2) " >
    <input type=button value="Continue timing" onClick="count2()" >
</form>

<script>
    count1()
    count2()
</script>
</body>
</html>

6. Conclusion

This is the end of this article about the usage summary of javascript's setTimeout(). For more information about the usage of javascript's setTimeout(), please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • What are the basic uses of JavaScript setTimeout()
  • JavaScript setInterval() vs setTimeout() Timers
  • JavaScript timer setTimeout() and setInterval() detailed explanation
  • Solution to the problem that setTimeout() cannot call functions with parameters in JS
  • Example to explain the usage of setTimeout() in JS
  • A brief analysis of the usage examples of setTimeout() and clearTimeout() in js
  • Issues to note when using the closure feature of Javascript's setTimeout()
  • Introduction and application of js setTimeout() function taking countdown as an example

<<:  Implementation of MySQL GRANT user authorization

>>:  Why can't my tomcat start?

Recommend

Vue virtual Dom to real Dom conversion

There is another tree structure Javascript object...

How to solve the synchronization delay caused by MySQL DDL

Table of contents Preface Solution Tool Introduct...

Three ways to prevent MySQL from inserting duplicate data

Create a new table CREATE TABLE `person` ( `id` i...

MySql sets the specified user database view query permissions

1. Create a new user: 1. Execute SQL statement to...

XHTML Getting Started Tutorial: Using the Frame Tag

<br />The frame structure allows several web...

A brief understanding of the difference between MySQL union all and union

Union is a union operation on the data, excluding...

How to add fields to a large data table in MySQL

Preface I believe everyone is familiar with addin...

How to Install Oracle Java 14 on Ubuntu Linux

Recently, Oracle announced the public availabilit...

How to use html2canvas to convert HTML code into images

Convert code to image using html2canvas is a very...

React native realizes the monitoring gesture up and down pull effect

React native implements the monitoring gesture to...

Summary of Docker Consul container service updates and issues found

Table of contents 1. Container service update and...

WeChat applet implements login interface

The login interface of WeChat applet is implement...

Detailed explanation of Linux file permissions and group modification commands

In Linux, everything is a file (directories are a...