setInterval的基本用法

9,651 阅读1分钟

简单用法

  • setInterval按照指定的周期调用函数
var interalFunc
function myFunction(){
	//3秒后调用alertFunc函数
   interalFunc = setInterval(alerFunc,3000)
}
function alertFunc(){
    alert('hello zf')
}
  • 使用clearInterval()来清楚计时器
清除计时器,计时器必须要有一个变量名
//设置计时器
var myInterval = setInterval(alert('hello Mcdonald',3000))
//清除计时器
clearInterval(myInterval)
  • 写一个动态进度条功能
window.onload = function move(){
  let ele = document.getElementById('moveBar');
  let width = 0;
  let moveInterval = setInterval(frame,1000)
  function frame(){
      if(width === 500){
          clearInterval(moveInterval)
      }else{
          width++;
          ele.style.width=width+'%'
          ele.innerText = width+'%'
      }
  }
}