1. setTimeout()
setTimeout函数用来指定某个函数或某段代码,在多少毫秒之后执行。它返回一个整数,表示定时器的编号,以后可以用来取消这个定时器。
var timerId = setTimeout(func|code, delay);
console.log(1);
setTimeout('console.log(2)',1000);
console.log(3);
// 1
// 3
// 2
除了前两个参数,setTimeout还允许更多的参数。它们将依次传入推迟执行的函数(回调函数)。
setTimeout(function(a,b){
console.log(a+b);
},1000,1,1)
var x = 1;
var obj = {
x: 2,
y: function () {
console.log(this.x);
}
};
setTimeout(obj.y, 1000) // 1
上面代码输出的是1,而不是2。因为当obj.y在1000毫秒后运行时,this所指向的已经不是obj了,而是全局环境。
解决方法是
setTimeout(function () {
obj.y();
}, 1000);
// 2
setTimeout(obj.y.bind(obj), 1000)
2. setInterval
setInterval的一个常见用途是实现轮询。下面是一个轮询 URL 的 Hash 值是否发生变化的例子。
var hash = window.location.hash;
var hashWatcher = setInterval(function(){
if (window.location.hash!= hash){updatePage()};
},1000)
3. clearTimeout() clearInterval()
var id1 = setTimeout(f, 1000);
var id2 = setInterval(f, 1000);
clearTimeout(id1);
clearInterval(id2);
setTimeout和setInterval返回的整数值是连续的,也就是说,第二个setTimeout方法返回的整数值,将比第一个的整数值大1
(function(){
// 每轮事件循环检查一次
var gid = setInterval(clearAllTimeouts, 0);
function clearAllTImeouts() {
var id = setTimeout(function(){}, 0);
where(id >0){
if(id ! = gid) {clearTimeout(id);} id --;
}
}
})
debounce
防抖动
$('textarea').on('keydown', debounce(ajaxAction, 2500));
function debounce(fn, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
clearTImeout(timer);
timer = setTime
}
}
setTimeout(f, 0)
1. 含义
setTimeout的作用是将代码推迟到指定时间执行,如果指定时间为0,即setTimeout(f,0)
setTimeout(f, 0)这种写法的目的是,尽可能早地执行f,但是并不能保证立刻就执行f。
document.getElementById('input-box').onkeypress = function (event) {
this.value = this.value.toUpperCase();
}
上面代码想在用户每次输入文本后,立即将字符转成大写。但是实际上,它只能将本次输入前的字符转为大写,因为浏览器此时还没有接受到新的文本,所以this.value 取不到最新输入的那个字符,只有用setTimeout改写,上面的代码才能发挥作用
document.getElementById('input-box').onkeypress = function() {
var self = this;
setTimeout(function(){
self.value = self.value.toUpperCase();
},0)
}
上面代码将代码放入setTimeout之中,就能使得它在浏览器接收到文本之后触发。
由于setTimeout(f, 0)实际上意味着,将任务放到浏览器最早可得的空闲时段执行,所以那些计算量大、耗时长的任务,常常会被放到几个小部分,分别放到setTimeout(f, 0)里面执行。