1. 延迟性定时器
1s后执行一次
setTimeout(function () {
console.log(1);
}, 1000);
2. 循环定时器
每隔1s执行1次
setInterval(function () {
console.log(1)
}, 1000);
3. 清除定时器
/*
clearInterval: 清除定时器
oBox.style.width:设置盒子宽度
getComputedStyle:获取显示样式
*/
var oBox = document.getElementsByClassName("box")[0];
var timer = setInterval(function () {
oBox.style.width = parseInt(getComputedStyle(oBox, null).width) + 20 + 'px';
if(parseInt(getComputedStyle(oBox, null).width) > 500){
// 清除定时器
clearInterval(timer);
}
}, 200);
4. 定时器中回调函数传参
var timer = setTimeout(function (a, b) {
console.log(a+b); // 5
}, 1000, 2,3);
5. 定时器是异步的
- 定时器,事件,ajax 都是异步的
- js是单线程执行的
- 在js中 先执行同步代码,然后执行异步代码
var timer = setTimeout(function () {
console.log(2);
}, 1000);
for(var i = 0; i< 1000; i++){
console.log(1);
}
来源:CSDN
作者:玩爬虫的小朋友
链接:https://blog.csdn.net/gklcsdn/article/details/103962605