Home Web Front-end JS Tutorial Detailed explanation of the usage of SetInterval and setTimeout in JavaScript_javascript skills

Detailed explanation of the usage of SetInterval and setTimeout in JavaScript_javascript skills

May 16, 2016 pm 03:33 PM

setTimeout

Description

setTimeout(code,millisec)

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

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

参数 描述
code 必需,要调用的函数后要执行的 JavaScript 代码串。
millisec 必需,在执行代码前需等待的毫秒数。

setTimeinterval

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

参数 描述
code 必需,要调用的函数或要执行的代码串。
millisec 必需,周期性执行或调用code之间的时间间隔,以毫秒计。

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

Set 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) sets a timeout object setInterval("function",time) sets a timeout object

SetInterval is automatically repeated, and setTimeout will not be repeated.

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

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

Use a timer to implement delayed 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>
Copy after login

This code will cause the dialog box "hello" to be displayed 5 seconds after the page is opened. 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>
Copy after login

In this way, if you want to cancel the display, you only need to click on any part of the page, and the window.clearTimeout method will be executed, so that the timeout operation will be cancelled.

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>
Copy after login

Passing parameters to the timer call, whether it is window.setTimeout or window.setInterval, cannot take parameters when using the function name as the calling handle. In many cases, parameters must be taken, which requires a solution. For example, for the function hello(_name), it is used to display a welcome message for the username: var userName="jack";

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

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

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

This will cause the hello function to execute immediately and pass the return value as the call handle to the setTimeout function. The result is not what the program needs. You can achieve the desired result by using string form:

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

The string here is a piece of JavaScript code, in which userName represents a variable. However, 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>

Copy after login

这里定义了一个函数_hello,用于接收一个参数,并返回一个不带参数的函数,在这个函数内部使用了外部函数的参数,从而对其调用,不需要使用参数。在window.setTimeout函数中,使用_hello(userName)来返回一个不带参数的函数句柄,从而实现了参数传递的功能。

window对象有两个主要的定时方法,分别是setTimeout 和 setInteval 他们的语法基本上相同,但是完成的功能取有区别。

  setTimeout方法是定时程序,也就是在什么时间以后干什么。干完了就拉倒。

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

  JS里设定延时:

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

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

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

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

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

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

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

例如:

tttt=setTimeout('northsnow()',1000);
clearTimeout(tttt);
Copy after login

或者:

tttt=setInterval('northsnow()',1000);
clearInteval(tttt);
Copy after login

举一个例子:

<div id="liujincai">
</div>
<input type="button" name="start" value="start" onclick='startShow();'>
<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>
Copy after login

或者:

<div id="liujincai">
</div>
<input type="button" name="start" value="start" onclick='timer2=window.setInterval("startShow()",2000);//startShow();'>
<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>
Copy after login

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

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 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.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles