Home  >  Article  >  Web Front-end  >  Timer usage of SetInterval and setTimeout in javascript

Timer usage of SetInterval and setTimeout in javascript

高洛峰
高洛峰Original
2017-02-08 15:48:541250browse

The setTimeout() method is used to call a function or calculated expression after a specified number of milliseconds, while setInterval() loops to call a function or expression every specified number of milliseconds until clearInterval clears it. In other words, setTimeout() is only executed once, and setInterval() can be executed multiple times. The parameters of the two functions are also the same. The first parameter is the code or handle to be executed, and the second parameter is the number of milliseconds to delay.

setTimeOut usage

The usage of the setTimeout function is as follows:

var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]); 
var timeoutID = window.setTimeout(code, [delay]);

timeoutID: timer ID number, it Can be used to clear the timer in the clearTimeout() function.

func: The function being executed.

code: (Alternative syntax) A string of code to be executed.

delay: delay time, in milliseconds. If not specified, defaults to 0.

We can use window.setTimeout or setTimeout. The two writing methods are basically the same, except that window.setTimeout refers to the setTimeout function as a property of the global window object.

Application example:

function timeout(){ 
 document.getElementById('res').innerHTML=Math.floor(Math.random()*100 + 1); 
} 

setTimeout("timeout()",5000);

When the code is executed, the timeout() function is called after 5 seconds.

setInterval usage

The parameters and usage of the setInterval function are the same as the setTimeout function. Please refer to the usage introduction of the setTimeout function above. The difference is that setInterval executes the func or code code at regular intervals.

Application example:

var tt = 10; 
function timego(){ 
 tt--; 
 document.getElementById("tt").innerHTML = tt; 
 if(tt==0){ 
  window.location.href='/'; 
  return false; 
 } 
} 

var timer = window.setInterval("timego()",1000);

Function timego() defines the content displayed by page element #tt. When tt equals 0, the page is oriented Go to the home page. Then we define a timer timer and use setInterval() to call timego() every 1 second. In this way, timego will be executed 10 times, and each time the number tt will be reduced by 1 until it is 0. Then if you want to stop the timer, you can use the following code:

window.clearInterval(timer);

When the code is executed, the page will jump to the homepage after 10 seconds.

In fact, setTimeout() can also execute a function repeatedly at regular intervals, but we still simply use setTimeOut and setInterval differently. In addition, JavaScript runs in the browser's JavaScript engine in a single-threaded manner. In actual applications, complex tasks need to be queued for execution, which may lead to inaccurate timers. This issue needs to be considered in large-scale applications. This article does not Do deep research.

Example 2:

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

Using a timer to implement delayed execution or repeated execution of JavaScript The window object provides two methods. To achieve the effect of the timer, they are window.setTimeout() and window.setInterval respectively. 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. At the specified time, the system will automatically call the function. 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.

如果想要取消定时执行,和clearTimeout方法类似,可以调用window.clearInterval方法。clearInterval方法同样接收一个setInterval方法返回的值作为参数。例如: //定义一个反复执行的调用 var id=window.setInterval("somefunction",10000); //取消定时执行
window.clearInterval(id); 上面的代码仅用于说明怎样取消一个定时执行。实际上在很多场合都需要用到setInterval方法,下面将设计一个秒表,来介绍setInterval函数的用途:该秒表将包括两个按钮和一个用于显示时间的文本框。当单击开始按钮时开始计时,最小单位为0.01秒,此时再次单击按钮则停止计时,文本框显示经过的时间。另外一个按钮用于将当前时间清零。其实现

代码如下:

<!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>

给定时器调用传递参数 无论是window.setTimeout还是window.setInterval,在使用函数名作为调用句柄时都不能带参数,而在许多场合必须要带参数,这就需要想方法解决。例如对于函数hello(_name),它用于针对用户名显示欢迎信息: var userName="jack";

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

这时,如果企图使用以下语句来使hello函数延迟3秒执行是不可行的:

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


这将使hello函数立即执行,并将返回值作为调用句柄传递给setTimeout函数,其结果并不是程序需要的。而使用字符串形式可以达到想要的结果:

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


这里的字符串是一段JavaScript代码,其中的userName表示的是变量。但这种写法不够直观,而且有些场合必须使用函数名,下面用一个小技巧来实现带参数函数的调用:


<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>

这里定义了一个函数_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);

或者:

tttt=setInterval('northsnow()',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>

虽然SetInterval与setTimeout都是用作定时器的,但它们的应用是有区别的。

更多javascript中SetInterval与setTimeout的定时器用法相关文章请关注PHP中文网!

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