定时器

僤鯓⒐⒋嵵緔 提交于 2020-01-14 14:49:26

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);
 }

在这里插入图片描述

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