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

Zabbix's psk encryption combined with zabbix_get value

Since Zabbix version 3.0, it has supported encryp...

MySQL database query performance optimization strategy

Optimize queries Use the Explain statement to ana...

Detailed explanation of the use of base tag in HTML

In requireJS, there is a property called baseURL....

Achieve 3D flip effect with pure CSS3 in a few simple steps

As a required course for front-end developers, CS...

Example of how to implement local fuzzy search function in front-end JavaScript

Table of contents 1. Project Prospects 2. Knowled...

Detailed tutorial for installing influxdb in docker (performance test)

1. Prerequisites 1. The project has been deployed...

Vue login function implementation

Table of contents Written in front Login Overview...

In-depth understanding of the role of Vuex

Table of contents Overview How to share data betw...

MySql 8.0.11-Winxp64 (free installation version) configuration tutorial

1. Unzip the zip package to the installation dire...

How to remove inline styles defined by the style attribute (element.style)

When modifying Magento frequently, you may encount...

Centos8.3, docker deployment springboot project actual case analysis

introduction Currently, k8s is very popular, and ...

Vue close browser logout implementation example

Table of contents 1. beforeunload event 2. Unload...

Summary of common docker commands (recommended)

1. Summary: In general, they can be divided into ...

Some functions of using tcpdump to capture packets in the Linux command line

tcpdump is a flexible and powerful packet capture...

Layui implements sample code for multi-condition query

I recently made a file system and found that ther...