search
HomeWeb Front-endJS TutorialDetailed explanation of the usage of SetInterval and setTimeout in JavaScript

setTimeout

Description

setTimeout(code,millisec)

setTimeout() method is used to specify The number of milliseconds after which to call a function or calculated expression.

Note: During the calling process, you can use clearTimeout(id_of_settimeout) to terminate


Parameters Description
code Required, the JavaScript code string to be executed after the function to be called.
millisec Required, the number of milliseconds to wait before executing the code.

setTimeinterval

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


##codeRequired, the function to be called or a string of code to be executed. millisecRequired, the time interval between periodic execution or calling code, in milliseconds.

The setInterval() method can call a function or calculate an expression according to a specified period (in milliseconds).

Setting the delay in JS:

Using SetInterval is very similar to setting the delay function setTimeout. setTimeout is used to delay for a period of time before performing an operation.

setTimeout("function",time) Set a timeout object setInterval("function",time) Set a timeout object

SetInterval is automatically repeated, and setTimeout will not repeat.

clearTimeout(object) clears the setTimeout object clearInterval(object) clears the setInterval object

The setInterval() method can call a function according to the specified period (in milliseconds) or Evaluate expressions.

Use timers to implement delayed execution or repeated execution of JavaScript. The window object provides two methods to achieve the effect of the timer, namely window.setTimeout() and window.setInterval. The former can make a piece of code run after a specified time; while the latter can make a piece of code run once every specified time. Their prototypes are as follows: window.setTimeout(expression,milliseconds); window.setInterval(expression,milliseconds); Among them, expression can be a piece of code enclosed in quotation marks, or it can be a function name. When the specified time is reached, the system will The function will be called automatically. When using the function name as the call handle, it cannot take any parameters; when using a string, you can write the parameters to be passed in it. The second parameter of the two methods is milliseconds, which represents the number of milliseconds for delay or repeated execution.

The two methods are introduced below.

1. window.setTimeout method This method can delay the execution of a function, for example:

<script language="JavaScript" type="text/javascript">
<!--
 function hello(){ alert("hello"); } window.setTimeout(hello,5000);
//-->
 </script>

This code will cause the page to display the dialog box "hello" after 5 seconds. ". The last sentence can also be written as: window.setTimeout("hello()",5000); Readers can appreciate their differences. This property also exists in the window.setInterval method. If you cancel the delayed execution before the delay period is reached, you can use the window.clearTimeout(timeoutId) method, which receives an id representing a timer. This id is returned by the setTimeout method, for example:

<script language="JavaScript" type="text/javascript">
<!--
function hello(){   
alert("hello");
}
var id=window.setTimeout(hello,5000);
document.onclick=function(){   
window.clearTimeout(id);
 }
//-->
</script>

In this way, if you want to cancel the display, you only need to click any part of the page to execute the window. The clearTimeout method causes the timeout operation to be canceled.

2. window.setInterval method This method causes a function to be called every fixed time and is a very common method. If you want to cancel scheduled execution, similar to the clearTimeout method, you can call the window.clearInterval method. The clearInterval method also receives a value returned by the setInterval method as a parameter. For example: //Define a call to be executed repeatedly var id=window.setInterval("somefunction",10000); //Cancel scheduled execution window.clearInterval(id); The above code is only used to illustrate how to cancel a scheduled execution. In fact, the setInterval method needs to be used on many occasions. Below we will design a stopwatch to introduce the use of the setInterval function: the stopwatch will include two buttons and a text box for displaying the time. When the start button is clicked, the timing starts. The minimum unit is 0.01 seconds. Clicking the button again will stop the timing, and the text box displays the elapsed time. Another button is used to reset the current time to zero. The implementation code is as follows:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
<head>
 <title> New Document </title>
 </head> 
<body> 
<form action="somepage.asp"> 
<input type="text" value="0" name="txt1"/> 
<input type="button" value="开始" name="btnStart"/> 
<input type="button" value="重置" name="btnReset"/> 
</form> 
</body> 
</html>

<script language="JavaScript" type="text/javascript">
<!--
//获取表单中的表单域
var txt=document.forms[0].elements["txt1"];
 var btnStart=document.forms[0].elements["btnStart"];
 var btnReset=document.forms[0].elements["btnReset"]
 //定义定时器的id
var id;
//每10毫秒该值增加1
var seed=0;
btnStart.onclick=function(){   
//根据按钮文本来判断当前操作   
 if(this.value=="开始"){       
 //使按钮文本变为停止       
 this.value="停止";       
//使重置按钮不可用       
 btnReset.disabled=true;       
//设置定时器,每0.01s跳一次       
id=window.setInterval(tip,10);    }
else{       
//使按钮文本变为开始       
this.value="开始";       
//使重置按钮可用       
 btnReset.disabled=false;       
//取消定时       
window.clearInterval(id);   
 } }
//重置按钮
btnReset.onclick=function(){   
seed=0;
 }
//让秒表跳一格
 function tip(){  
  seed++;   
 txt.value=seed/100;
}
//-->
</script>

Passing parameters to the timer call, whether it is window.setTimeout or window.setInterval, cannot be used when using the function name as the calling handle With parameters, and in many situations it is necessary to take parameters, so we need to find a way to solve it. For example, the function hello(_name) is used to display the welcome message for the user name: var userName="jack";

//根据用户名显示欢迎信息
function hello(_name){   
 alert("hello,"+_name);
 }

At this time, if you try to use The following statement is not feasible to delay the execution of the hello function for 3 seconds:

window.setTimeout(hello(userName),3000);

This will cause the hello function to be executed immediately and will return The value is passed to the setTimeout function as a call handle, and the result is not what the program needs. The desired result can be achieved by using the string form:

window.setTimeout("hello(userName)",3000);

The string here is a piece of JavaScript code, in which userName represents a variable. But this way of writing is not intuitive enough, and in some cases function names must be used. Here is a little trick to call a function with parameters:

<script language="JavaScript" type="text/javascript"> <!-- var userName="jack";
//根据用户名显示欢迎信息
function hello(_name){    
alert("hello,"+_name);
}
//创建一个函数,用于返回一个无参数函数
function _hello(_name){    
return function(){       
hello(_name);    } }
window.setTimeout(_hello(userName),3000);
 //-->
</script>

It is defined here A function _hello is used to receive a parameter and return a function without parameters. The parameters of the external function are used inside this function, so that it is called without using parameters. In the window.setTimeout function, use _hello(userName) to return a function handle without parameters, thus realizing the parameter passing function.

The window object has two main timing methods, namely setTimeout and setInteval. Their syntax is basically the same, but the completed functions are different.

The setTimeout method is a timing program, that is, what to do after a certain time. Pull it down when you're done.

  setInterval方法则是表示间隔一定时间反复执行某操作。

  JS里设定延时:

使用SetInterval和设定延时函数setTimeout 很类似。setTimeout 运用在延迟一段时间,再进行某项操作。

setTimeout("function",time) 设置一个超时对象

setInterval("function",time) 设置一个超时对象

SetInterval为自动重复,setTimeout不会重复。

clearTimeout(对象) 清除已设置的setTimeout对象

clearInterval(对象) 清除已设置的setInterval对象

如果用setTimeout实现setInerval的功能,就需要在执行的程序中再定时调用自己才行。如果要清除计数器需要根据使用的方法不同,调用不同的清除方法:

例如:

tttt=setTimeout(&#39;northsnow()&#39;,1000);
clearTimeout(tttt);

或者:

tttt=setInterval(&#39;northsnow()&#39;,1000);
clearInteval(tttt);

举一个例子:

<p id="liujincai">
</p>
<input type="button" name="start" value="start" onclick=&#39;startShow();&#39;>
<input type="button" name="stop" value="stop" onclick="stop();">
<script language="javascript">  
var intvalue=1;  
var timer2=null;  
function startShow()  {   
 liujincai.innerHTML=liujincai.innerHTML + " " + (intvalue ++).toString();   
timer2=window.setTimeout("startShow()",2000);  }  
function stop()  {   
 window.clearTimeout(timer2);  
 }
</script>

或者:

<p id="liujincai">
</p>
<input type="button" name="start" value="start" onclick=&#39;timer2=window.setInterval("startShow()",2000);//startShow();&#39;>
<input type="button" name="stop" value="stop" onclick="stop();">
<script language="javascript">  
 var intvalue=1;  
var timer2=null;  
 function startShow()  {   
 liujincai.innerHTML=liujincai.innerHTML + " " + (intvalue ++).toString();  
 }  
 function stop()  {   
 window.clearInterval(timer2);  
}
</script>

以上内容是小编给大家介绍的关于JavaScript中SetInterval与setTimeout的用法详解,希望对大家学习SetInterval与setTimeout的相关知识有所帮助。

更多JavaScript中SetInterval与setTimeout的用法详解相关文章请关注PHP中文网!

Parameters Description
Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor