window对象的定时器

一.setInterval()

如果我们希望一段程序可以每隔一段时间执行一次, 这就用到了我们的定时器.

setInterval()
------ 可以将一个函数每隔一段时间执行一次.
------ 参数:1. 回调函数, 该函数每隔一段时间会被调用一次
------ 2. 调用回调函数的时间间隔
------ 返回值: 一个Number型的数字, 这个数字作为定时器的唯一标识
------ 注意, 第一次调用回调函数会等一个参数时间间隔

clearInterval(timer) 可以关闭一个timer标识的setInterval()定时器

1.定时调用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<head>
<meta charset="UTF-8">
<script type="text/javascript">
window.onload = function() {
var text = document.getElementById("text");
var num = 1;
var timer = setInterval(function(){
text.innerHTML = num++;
if(num==11){
clearInterval(timer);
}
},500);
}
</script>
</head>
<body>
<span id="text"></span>
</body>

2.移动div

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<head>
<meta charset="UTF-8">
<script type="text/javascript">
window.onload = function() {
var box = document.getElementById("box");
var div = 0;
var speed = 10;
var timer = setInterval(function() {
switch (div) {
case 37:box.style.left = box.offsetLeft - speed + "px";break;
case 38:box.style.top = box.offsetTop - speed + "px";break;
case 39:box.style.left = box.offsetLeft + speed + "px";break;
case 40:box.style.top = box.offsetTop + speed + "px";break;
}
}, 30);
document.onkeydown = function(event) {
event = event || window.event;
if (event.altKey)speed = 100;
else speed = 10;
div = event.keyCode;
document.onkeyup = function() {
div = 0;
};
};
}
</script>
</head>
<body>
<div id="box" style="width:100px;height:100px;background-color:red;position:absolute;"></div>
</body>

二.延时调用

延时调用: 延时调用一个函数, 不会马上执行, 而是隔一段时间之后在执行, 且只会执行一次

延时调用与定时调用的区别, 定时调用会多次调用回调函数, 延时调用只会调用一次

延时调用和定时调用实际上可以互相代替

延时调用用setTimeout()函数实现

1.setTimeout()

1
2
3
4
5
var num = 1;
var timer = setTimeout(function(){
console.log(num++);//1s后打印
},1000);
cleanTimeout(timer);//关闭定时器

评论