setTimeout和setInterval

邮差的信 提交于 2019-11-29 01:57:45

1.setTimeout

1)第一个参数

// 第一个参数不仅可以是function, 还可以是一段可执行代码的字符串格式
setTimeout('console.log(1)', 1000); // 一秒后打印1
// 如果上面的代码没有字符串包含,则会立即打印,定时器不起效果
setTimeout(function timer() {
  console.log(1);
},1000); // 效果和上面的字符串功能相同

2) 第二个参数

setTimeout(fn) 等同于 setTimeout(fn, 0);
// 第二个参数没有的时候默认是0,但其实是等于4ms

3)第三个及之后的参数

setTimeout(function timer(a,b) {
  console.log(a,b); // 1,2
}, 1000, 1,2); 
// 当有第三个及之后的参数时,作为回调函数的参数传入

4) 返回值

// 返回一个数字,表示定时器编号,数字以此加1
const a = setTimeout(fn, 1000); // a =4
const b = setTimeout(fn, 1000); // b = 5
const c = setTimeout(fn, 1000); // c = 6

5) 关于this

// this可以理解成调用该函数的对象
// 1) 直接写入回调函数
setTimeout(function timer() {
   console.log(this); // window, 也可说明timer有个涵盖全局作用域的闭包
})
// 2)回调函数是对象的方法
var obj = {
    x: 1,
    y: function() {
        console.log(this.x);
    }
}
setTimeout(obj.y,1000) // undefined  等同于1)中的写法
setTimeout(obj.y(), 1000) // 立即打印1
setTimeout('obj.y()', 1000); // 1
setTimeout(function() {
    obj.y(); // 1
}, 1000);

2. setInterval

1.参数之类的同setTimeout

2.应用

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!