定时器
setInterval(function,num) 多次循环执行
function 函数
num 时间单位为 毫秒 1000毫秒等于1秒
setTimeout(fun
ction,num) 只执行一次
setInterval(function,num) 多次循环执行
function 函数
num 时间单位为 毫秒 1000毫秒等于1秒
setTimeout(fun
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
#box{
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div id="box">
</div>
</body>
</html>
<script>
/*
定时器
setInterval(function,num) 多次循环执行
function 函数
num 时间单位为 毫秒 1000毫秒等于1秒
setTimeout(function,num) 只执行一次
*/
var oBox = document.querySelector('#box');
// var w = 100;
// var time = setInterval(function(){
// w+=5
// console.log(time)
// if(w >= 500){
// // 清除定时器
// clearInterval(time);
// }
// oBox.style.width = w + 'px';
// },1000/60)
// //1000/60 一秒钟执行60次
// oBox.onclick = fn;
// function fn(){
// var time2 = setTimeout(function(){
// alert('我只执行一次');
// },500)
// //清除定时器
// clearTimeout(time2)
// }
//定时器中的 --- this ---
// oBox.onclick = function(){
// console.log(this)//指向 盒子 oBox
// function fn(){
// console.log(this)//指向 window
// }
// fn()
// }
// oBox.onclick = function(){
// console.log(this)//指向 盒子 oBox
// setInterval(function(){
// console.log(this)
// //通过 bind 绑定当前盒子的this ,为定时器的this
// }.bind(this),1000)
// }
// 这样先马上调用一次
// fun2();
// setInterval(fun2,2000)
// // setInterval(fun2(),2000);
// // 如果这么写 加() 有两个问题
// // 一.会马上调用方法
// // 二.只会调用一次
// function fun2(){
// console.log(this);
// }
//解决方案 返回自身函数
//实现 立刻执行一次,两秒钟执行一次
setInterval(fun2(),2000);
function fun2(){
console.log(this);
return fun2;
}
</script>
ction,num) 只执行一次