定义和用法
setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。
setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。
语法
setInterval(code,millisec[,"lang"])
参数 | 描述 |
---|---|
code | 必需。要调用的函数或要执行的代码串。 |
millisec | 必须。周期性执行或调用 code 之间的时间间隔,以毫秒计。 |
返回值
一个可以传递给 Window.clearInterval() 从而取消对 code 的周期性执行的值。
实例
<html> <body> <input type="text" id="clock" size="35" /> <script language=javascript> var int=self.setInterval("clock()",50)
function clock() { var t=new Date() document.getElementById("clock").value=t } </script> </form> <button οnclick="int=window.clearInterval(int)">
Stop interval</button> </body> </html>
现附上实时显示当前系统时间的代码:
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
< head runat ="server" >
< title > </title>
</head>
< body >
< form id ="form1" runat ="server" >
< div >
< div id ="idTime" > </div>
< script >
/*date*/
function GetTime() {
var d = new Date(), sResult = d.getYear() + "年 " + (d.getMonth() + 1) + "月 " + d.getDate() + "日 星期";
switch (d.getDay()) {
case 0:
sResult += "天";
break;
case 1:
sResult += "一";
break;
case 2:
sResult += "二";
break;
case 3:
sResult += "三";
break;
case 4:
sResult += "四";
break;
case 5:
sResult += "五";
break;
case 6:
sResult += "六";
break;
}
return sResult + " " + Right(("0" + d.getHours()), 2) + ":" + Right(("0" + d.getMinutes()), 2) + ":" + Right(("0" + d.getSeconds()), 2);
}
function Right(string, length) { return string.substring(string.length - length); }
/*日期*/
var oTime = document.getElementById("idTime");
oTime.innerHTML = GetTime();
setInterval(function() { oTime.innerHTML = GetTime(); }, 1000)
</script>
</div>
</form>
</body>
</html>
< head runat ="server" >
< title > </title>
</head>
< body >
< form id ="form1" runat ="server" >
< div >
< div id ="idTime" > </div>
< script >
/*date*/
function GetTime() {
var d = new Date(), sResult = d.getYear() + "年 " + (d.getMonth() + 1) + "月 " + d.getDate() + "日 星期";
switch (d.getDay()) {
case 0:
sResult += "天";
break;
case 1:
sResult += "一";
break;
case 2:
sResult += "二";
break;
case 3:
sResult += "三";
break;
case 4:
sResult += "四";
break;
case 5:
sResult += "五";
break;
case 6:
sResult += "六";
break;
}
return sResult + " " + Right(("0" + d.getHours()), 2) + ":" + Right(("0" + d.getMinutes()), 2) + ":" + Right(("0" + d.getSeconds()), 2);
}
function Right(string, length) { return string.substring(string.length - length); }
/*日期*/
var oTime = document.getElementById("idTime");
oTime.innerHTML = GetTime();
setInterval(function() { oTime.innerHTML = GetTime(); }, 1000)
</script>
</div>
</form>
</body>
</html>
转载于:https://blog.51cto.com/visionsky/314844