setTimeout
语法规范:window.setTimeout(调用函数,延时时间);
window在调用时可以省略。
这个延时时间单位是毫秒 ,如果省略默认的是0。
这里的调用函数可以直接写函数,也可以写函数名。还可以采取字符串,'函数名()'。三种形式,第三种不推荐。
页面中可能有很多的定时器,我们经常给定时器加标识符,用来区别不同的定时器。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
setTimeout(function() {
console.log('时间到了');
}, 2000);
function callback() {
console.log('爆炸了');
}
setTimeout(callback, 3000);
var time1 = setTimeout(callback, 3000);
var time2 = setTimeout(callback, 5000);
</script>
</body>
</html>
5秒后自动关闭广告的例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<img src="images/ad.jpg" class="ad" >
<script type="text/javascript">
var ad = document.querySelector('.ad');
window.setTimeout(function(){
ad.style.display = 'none';
}, 5000);
</script>
</body>
</html>
停止setTimeout()定时器。
window.clearTimeout(timeoutID)
clearTimeout()方法取消了先前通过调用setTimeout()建立的定时器。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button type="button">点击停止定时器</button>
<script type="text/javascript">
var btn = document.querySelector('button');
var timer = setTimeout(function() {
console.log('爆炸了');
},5000);
btn.addEventListener('click', function() {
window.clearTimeout(timer);
});
</script>
</body>
</html>
window可以省略,里面的参数就是定时器的标识符。即我们给定时器所起的名字。