JavaScrip之----定时器

在js中的定时器分两种:1、setTimeout() 2、setInterval()

定时器的使用

不是js的内容属于浏览器的

setTimeout (表达式,延时时间) : 设置在延迟多少时间执行一次一个表达式

clearTimeout(名); 设置清除这个延迟器

1.setTimeOut()                                                          

只在指定时间后执行一次

/定时器 异步运行  
function hello(){  
alert("hello");  
}  
//使用方法名字执行方法  
var t1 = window.setTimeout(hello,1000);  
var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法  
window.clearTimeout(t1);//去掉定时器

 2.setInterval()                                                           

在指定时间为周期循环执行

/实时刷新  时间单位为毫秒  
setInterval('refreshQuery()',8000);   
/* 刷新查询 */  
function refreshQuery(){  
  console.log('每8秒调一次') 
}

      注意如果要求在每隔一个固定的时间,间隔后就精确地执行某动作,最好使用setInterval,如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,最好使用setTimeout

案例;

<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		#box{
			width: 100px;
			height: 100px;
			background-color: red;
		}
	</style>
</head>
<body>
	<button id="start">开启定时器</button>
	<button id="clear">清除定时器</button>

	<div id="box"></div>
 <script>
var count = 0;
	 	var timer = null;
	 	document.getElementById('start').onclick = function() {

	 		var oDiv = document.getElementById('box');
	 		clearInterval(timer);
	 		
	 		timer = setInterval(function() {
	 			count+=10;

	 			oDiv.style.marginLeft = count + 'px';
	 			
	 		}, 50)

	 	}



	 </script>
</body>
</html>

 

 

posted @ 2018-09-27 20:33  时光若止~~~  阅读(96)  评论(0编辑  收藏  举报