javascript setTimeout setInterval 和 clearInterval 的使用

69 篇文章 0 订阅
10 篇文章 0 订阅


setTimeout method

Evaluates an expression after a specified number of milliseconds has elapsed.

Syntax

var retval = window.setTimeout(expression, msec, language);

Parameters

expression [in]

Type: Variant

Variant that specifies the function pointer or string that indicates the code to be executed when the specified interval has elapsed.

msec [in]

Type: Integer

Integer that specifies the number of milliseconds.

language [in, optional]

Type: Variant

String that specifies one of the following values:

JScript

Language is JScript.

VBScript

Language is VBScript.

JavaScript

Language is JavaScript.

Return value

Type: Integer

Integer. Returns an identifier that cancels the evaluation with the clearTimeout method.

Standards information

There are no standards that apply here.

Remarks

The specified expression or function is evaluated once. For repeated evaluation, use the setInterval method.

When you use the setTimeout method with Introduction to DHTML Behaviors, the value of expression should be a function pointer to call a function within the HTML Component (HTC) file or a string to call a function in the primary document.

Note  In Windows Internet Explorer, you cannot pass arguments to the callback function directly; however, you can simulate passing arguments by creating an anonymous closure function that references variables within scope of the call to  setInterval or  setTimeout. For more information, see  setInterval.
 

The first argument of setTimeout can be a string or a function pointer.

Examples

The following example uses the setTimeout method to evaluate a simple expression after one second has elapsed.

window.setTimeout("alert('Hello, world')", 1000);

The following example uses the setTimeout method to evaluate a slightly more complex expression after one second has elapsed.

var sMsg = "Hello, world";
window.setTimeout("alert(" + sMsg + ")", 1000);

This example uses the setTimeout method to hide a input type=button object after three seconds. If the user clicks the Count Down button and then counts to three, the Now You See Me button disappears.

<script type="text/javascript">
function fnHide(oToHide){
   window.setTimeout("fnHide2(" + oToHide.id + ")", 3000);
}
function fnHide2(sID){
   var o = eval(sID);
   o.style.display="none";
}
</script>
<input type="button" value="Count Down" 
    id="oHideButton" οnclick="fnHide(this)">

This example uses a function pointer to pass the data. In this case, the data is stored in a global variable because it cannot be passed directly. In the preceding example, the id of the button is passed as a parameter to the function invoked by the setTimeout method. This is possible only when a string is passed as the first argument.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/setTimeout.htm

<script type="text/javascript">
var g_oToHide = null;
function fnHide(oToHide){
    g_oToHide = oToHide;
    window.setTimeout(fnHide2, 3000);
}
function fnHide2(sID){
    if (g_oToHide) {
       g_oToHide.style.display="none";
    }
}
</script>
<input type="button" value="Now you see me ..." 
    id="oHideButton" οnclick="fnHide(this)">

See also

window clearTimeout requestAnimationFrame setImmediate setInterval

setInterval method

Evaluates an expression each time a specified number of milliseconds has elapsed.

Syntax

var retval = window.setInterval(expression, msec, language);

Parameters

expression [in]

Type: Variant

Variant that specifies a function pointer or string that indicates the code to be executed when the specified interval has elapsed.

msec [in]

Type: Integer

Integer that specifies the number of milliseconds.

language [in, optional]

Type: Variant

String that specifies any one of the possible values for the LANGUAGE attribute.

Return value

Type: Integer

Integer. Returns an identifier that cancels the timer with the clearInterval method.

Standards information

There are no standards that apply here.

Remarks

The setInterval method continuously evaluates the specified expression until the timer is removed with the clearInterval method.

To pass a function as a string, be sure to append the function name with parentheses.

window.setInterval("someFunction()", 5000);

When passing a function pointer, do not include the parentheses.

window.setInterval(someFunction, 5000);

When you use the setInterval method with Introduction to DHTML Behaviors, the value of expression should be a function pointer to call a function within the HTML Component (HTC) file or a string to call a function in the primary document.

Note  In Windows Internet Explorer, you cannot pass arguments to the callback function directly; however, you can simulate passing arguments by creating an anonymous closure function that references variables within scope of the call to  setInterval or  setTimeout. For more information, see Examples.
 

In versions earlier than Microsoft Internet Explorer 5, the first argument of setInterval must be a string. Evaluation of the string is deferred until the specified interval elapses.

As of Internet Explorer 5, the first argument of setInterval can be passed as a string or as a function pointer.

Examples

This example uses the setInterval method to create a DHTML clock. A variable is assigned to the interval, and can be used as a reference to stop the interval by using the clearInterval method.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/setInterval.htm

var oInterval = "";
function fnStartClock(){
   oInterval = setInterval(fnDoClock,200);
}
function fnDoClock(){
   // Code to display hours, minutes, and seconds.
}
window.onload = fnStartClock; 

The next example demonstrates how to pass arguments to a function with setTimeout or setInterval. To do this, create an inner anonymous function to wrap the real callback function. In the new function scope, you can refer to variables declared prior to the call to setTimeout (such as div). This structure is referred to as a "closure" in JScript

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/setInterval2.htm

// The first example of a closure passes the variable to a named function.
function startTimer() {
    var div = document.getElementById('currentTime');
    setTimeout(function(){doClock(div)},200);
}
// The second example also uses a closure, by referring to an argument passed to the function.
function doClock(obj) {
    setInterval(function(){obj.innerHTML=(new Date()).toLocaleString()},200);
} 

This example demonstrates that more than one closure can refer to the same variable. Here, the callback function that displays the value of count is called at a different interval than the function that updates its value.

function startCounter() {
    var div = document.getElementById('counter');
    var count = 0;
    setInterval(function(){count++},143);
    setInterval(function(){div.innerHTML=count},667);
} 

See also

window Reference clearInterval requestAnimationFrame setTimeout setImmediate

clearInterval method

Cancels the interval previously started using the setInterval method.

Syntax

var retval = window.clearInterval(timerID);

Parameters

timerID [in]

Type: Integer

Integer that specifies the interval to cancel. This value must have been previously returned by the setInterval method.

Return value

Type: HRESULT

If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

Standards information

There are no standards that apply here.

See also

window setInterval


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>setInterval Method Sample</title>
<meta http-equiv="Content-Type" content="text/html; CHARSET=iso-8859-1">
<meta name="AUTHOR" content="InetSDK">
<meta name="MS.LOCALE" content="EN-US">
<meta name="ROBOTS" content="noindex">
<script type="text/javascript">
	var oInterval = "";
	function fnStartInterval()
	{
		if (oInterval == "")
		{
			oTimer.innerHTML = "Interval Started";
			oInterval = window.setInterval("fnRecycle()", 1000);
		}
		else
		{
			fnStopInterval();
		}
	}
	function fnStopInterval()
	{
		if (oInterval != "")
		{
			window.clearInterval(oInterval);
			oInterval = "";
			oTimer.innerHTML = "Interval Stopped";
		}
	}
	function fnRecycle()
	{
		var oDate = new Date();
		var sSwitch = "am";
		var iHours = oDate.getHours();
		if (iHours > 12)
		{
			iHours -= 12;
			sSwitch = "pm";
		}
		var sMinutes = oDate.getMinutes() + "";
		if (sMinutes.length == 1)
		{
			sMinutes = "0" + sMinutes;
		}
		var sSeconds = oDate.getSeconds() + "";
		if (sSeconds.length == 1)
		{
			sSeconds = "0" + sSeconds;
		}
		oTimer.innerHTML = iHours + ":" + sMinutes + ":" + sSeconds + " " + sSwitch;

	}
</script>
<!-- SAMPLE_STYLE_START -->
<link rel="stylesheet" href="samplesSDKIE4.css" type="text/css">
<!-- SAMPLE_STYLE_END -->
</head>

<!--TOOLBAR_START-->
<!--TOOLBAR_EXEMPT-->
<!--TOOLBAR_END-->
<body>

	<div class="body">
		<h1>setInterval Method Sample</h1>
		<p>
			The <b>setInterval</b> method invokes a function or line of code every time the specified amount of time passes. In this
			sample, a function is called to update the <b>innerHTML</b> property of a <b>span</b> with the current time every 1000
			milliseconds, or every second. Click Start Interval to invoke the <b>setInterval</b> method. Click Stop Interval to remove the
			interval with the <b>clearInterval</b> method.
		</p>
		<span id="oTimer" style="font-size: 16pt; font-weight: bold; font-family: Times; color: #0000FF;"> Interval Stopped</span>
		<p>
			<input type="button" value="Start Interval" οnclick="fnStartInterval()"> <input type="button" value="Stop Interval"
				οnclick="fnStopInterval()">
			<!-- START_PAGE_FOOTER -->
			<br> <br> <br>
		</p>
		<p class="viewsource">[Right-click and choose View Source from the shortcut menu.]</p>
		<a class="copyright" href="http://www.microsoft.com/isapi/gomscom.asp?TARGET=/info/cpyright.htm"> © 2007 Microsoft
			Corporation. All rights reserved. Terms of use.</a>
		<!-- END_PAGE_FOOTER -->
	</div>

</body>

</html>


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>setTimeout Method Sample</title>
<meta http-equiv="Content-Type" content="text/html; CHARSET=iso-8859-1">
<meta name="AUTHOR" content="InetSDK">
<meta name="MS.LOCALE" content="EN-US">
<meta name="ROBOTS" content="noindex">
<script type="text/javascript">
	function fnHide()
	{
		window.setTimeout("fnHide2()", 3000);

	}
	function fnHide2()
	{
		oHideButton.style.display = "none";
		oShowButton.style.display = "";
	}
</script>
<!-- SAMPLE_STYLE_START -->
<link rel="stylesheet" href="samplesSDKIE4.css" type="text/css">
<!-- SAMPLE_STYLE_END -->
</head>

<!--TOOLBAR_START-->
<!--TOOLBAR_EXEMPT-->
<!--TOOLBAR_END-->
<body>

	<div class="body">
		<h1>setTimeout Method Sample</h1>
		<p>
			This sample demonstrates the use of the <b>setTimeout</b> method. When the Click to Hide button is clicked, a timeout is set on
			the <b>window</b> object for a specified number of milliseconds. After that amount of time has elapsed, the function defined as
			a string is evaluated.
		</p>
		<p>
			<input type="button" value="Click to Hide" οnclick="fnHide()" id="oHideButton">
		</p>
		<p>
			When the Click to Hide button disappears (the <b>display</b> property is set to <i>none</i>), a second button is displayed
			allowing you to show the first button again.
		</p>
		<p>
			<input type="button" value="Show Button" id="oShowButton" style="display: none;"
				οnclick="oHideButton.style.display='';this.style.display='none';">
		</p>
		<!-- START_PAGE_FOOTER -->
		<br> <br> <br>
		<p class="viewsource">[Right-click and choose View Source from the shortcut menu.]</p>
		<a class="copyright" href="http://www.microsoft.com/isapi/gomscom.asp?TARGET=/info/cpyright.htm"> © 2007 Microsoft
			Corporation. All rights reserved. Terms of use.</a>
		<!-- END_PAGE_FOOTER -->
	</div>

</body>

</html>


https://msdn.microsoft.com/en-us/library/ms536753(v=vs.85).aspx

https://msdn.microsoft.com/en-us/library/ms536749(v=vs.85).aspx

https://msdn.microsoft.com/en-us/library/ms536353(v=vs.85).aspx


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值