JS中的定时器

JS的定时器相关的API有四个,分别是setTimeout、clearTimeout、setInterval、clearInterval。其中 setTimeout和clearTimeout是一组,setInterval 和 clearInterval是一组。javascript

setTimeout

设置一个定时器,定时器在定时器到期后执行一个函数或指定的一段代码java

let timerId = setTimeout(function[,delay,arg1,...,argn])
let timerId = setTimeout(code[,delay])

参数说明:
function: 定时器到期(delay毫秒)想要执行的函数
code[不推荐]: 定时器到期(delay毫秒)想要执行的字符串
delay[可选]:延迟的毫秒数,函数或者代码的执行在该延迟以后发生。若是不传值,则默认为0.注意:实际的延长时间可能会比期待的时间要长
arg1,...,argn[可选]:附加参数,定时器到期后会做为参数传给函数。segmentfault

返回值:
返回值timerId是一个正整数,表示定时器的编号,能够传给clearTimeout,用来取消该定时器。app

setInterval

设置一个时间间隔,每隔固定的时间间隔,重复的调用一个函数或指定的一段代码函数

let timerId = setInterval(function,delay[,arg1,...,argn])
let timerId = setInterval(code,delay)

参数说明:
function:每隔固定的间隔时间须要重复执行的函数
code[不推荐]:每隔固定的时间间隔须要重复执行的一段代码
delay:每次延迟的毫秒数,函数的每次调用会在该延迟以后发生。当参数值小于10的时候,会默认使用10.和setTimeout相同,实际的延长时间可能会更长
arg1,...,argn[可选]:附加参数,定时器到期后会做为参数传给函数this

返回值:
返回值timerId是一个正整数,表示定时器的编号,能够传给clearInterval,用来取消定时器。code

定时器使用的场景

重复执行repeat
例如: 每一个10ms输出一段指定的文字blog

function repeat(func, count = 0, delay = 10) {
  return function () {
    let repeatCount = 0;
    let args = arguments;
    let timerId = setInterval(() => {
      if (repeatCount++ < count) {
       func.apply(null, args)
      } else {
       clearInterval(timerId)
      }
    }, delay)
    return timerId;
  }
}

防抖函数debounce
防抖:在事件被触发n秒后再执行回调,若是在n秒内又被触发,则从新计时事件

function debounce(func, delay) {
  let timerId = null;
  let self = this;
  return (...args) => {
    if (timerId) {
      clearTimeout(timerId);
    }
    timerId = setTimeout(() => {
      func.apply(self, args);
    },delay)
  }
}

节流函数throttle
节流:规定在n秒内只能触发一次函数,屡次触发只会响应一次ip

function throttle(func, delay) {
  let timerId = null;
  let self = this;
  return (...args) => {
    if (timerId) {
      return;
    }
    timerId = setTimeout(() => {
      func.apply(self, args);
      clearTimeout(timerId)
    }, delay)
  }
}

参考文档:
setTimeout MDN
setInterval MDN
https://johnresig.com/blog/how-javascript-timers-work/
完全弄懂函数防抖和函数节流

相关文章
相关标签/搜索