JS定时器

 window提供了如下4个方法来支持定时器。

setInterval("code" , interval)、clearlnterval (timer)设置、删除定时器。setInterval设置每隔interval毫秒重复执行一次code。
setTimeout("code",interval)、clearTimeout(timer)也是设置定时器。推荐使用setInterval()和clearInterval ()。 setTimeout 设置在interval 毫秒延迟后执行一 次
<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title> 使用定时器 </title>
</head>
<body onload="setTime();">
	<span id="tm"></span>
	<script type="text/javascript">
		// 定义定时器变量
		var timer;
		// 保存页面运行的起始时间
		var cur = new Date().getTime(); 
		var setTime = function()
		{
			// 在tm元素中显示当前时间
			document.getElementById("tm").innerHTML = 
				new Date().toLocaleString();
			// 如果当前时间比起始时间大于60秒,停止定时器的调度
			if (new Date().getTime() - cur > 60 * 1000)
			{
				// 清除timer定时器
				clearInterval(timer);
			}
		}
		// 指定每隔1000毫秒执行setTime()函数一次
		timer = setInterval("setTime();" , 1000);
	</script>
</body>
</html>

 

 

<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title> 使用定时器 </title>
</head>
<body>
	<span id="tm"></span>
	<script type="text/javascript">
		// 定义定时器变量
		var timer;
		// 保存页面运行的起始时间
		var cur = new Date().getTime(); 
		var setTime = function()
		{
			// 在tm元素中显示当前时间
			document.getElementById("tm").innerHTML
				= new Date().toLocaleString();
			// 如果当前时间比起始时间小于等于60秒,执行定时器的调度
			if (new Date().getTime() - cur <= 60 * 1000)
			{
				// 指定延迟1000毫秒后执行setTime()函数。
				window.setTimeout("setTime();" , 1000);
			}
		}
		// 直接调用setTime()函数
		setTime();
	</script>
</body>
</html>

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值