定时器
在js中的定时器分两种:1、setTimeout() 2、setInterval()
定时器在js中式无法自动清除的 想要自己手动清除 以防止 占用内存过多 所以要记得使用了定时器 要记得清除了定时器
1.setTimeOut()
只在指定时间后执行一次
setTimeOut()是异步进行的
格式:
定时器(function(){执行内容},间隔时间)
它的间隔时间是以1000来表示1秒的
下面就是一个间隔打印的
<body>
<div class="box" id="box1"></div>
<script type="text/javascript">
window.onload = function(){
var c = document.getElementById('box1');
c.onmouseenter=function () {
console.log(33);
};
setTimeout(function(){
console.log(44);
},2000);
console.log(555);
}
</script>
</body>
setTimeout()多用来解决异步的 它在等待的时候也会去执行其他的内容的 等你的间隔好了就会输出
document.write(333); setTimeout(function(){ document.write(444); },3000) document.write(555);
2.setInterval()
在指定时间为周期循环执行
/实时刷新 时间单位为毫秒
setInterval('refreshQuery()',8000);
/* 刷新查询 */
function refreshQuery(){
console.log('每8秒调一次')
}
两种方法根据不同的场景和业务需求择而取之,
对于这两个方法,需要注意的是如果要求在每隔一个固定的时间间隔后就精确地执行某动作,那么最好使用setInterval,而如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,那么最好使用setTimeout
做一个移动的小盒子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app" style="width: 100px;height: 100px;border: 1px solid red;"></div>
<button id="move">移动</button>
<script type="text/javascript">
var oApp = document.getElementById('app');
var moveBtn = document.getElementById('move');
// var a = 10;
// var b = 20;
console.log(111);
// click
// document.getElementById('app').onclick = function(){
//}
// 异步 调用 只调用一次
var c = function(){
console.log(222);
}
setTimeout(function(){
console.log(222);
},2000);
console.log(333);
// var b = 20;
var count = 0;
var timer = null;
moveBtn.onclick = function(){
timer = setInterval(function(){
count+=3;
if (count>=500) {
clearInterval(timer);
}
// console.log(count);
oApp.style.marginLeft = count + 'px';
},50);
}
</script>
</body>
</html>


浙公网安备 33010602011771号