关于javascript:JS中的定时器

4次阅读

共计 1633 个字符,预计需要花费 5 分钟才能阅读完成。

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

setTimeout

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

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

参数阐明:
function: 定时器到期 (delay 毫秒) 想要执行的函数
code[不举荐]: 定时器到期(delay 毫秒) 想要执行的字符串
delay[可选]: 提早的毫秒数,函数或者代码的执行在该提早之后产生。如果不传值,则默认为 0. 留神:理论的延长时间可能会比期待的工夫要长
arg1,…,argn[可选]: 附加参数,定时器到期后会作为参数传给函数。

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

setInterval

设置一个工夫距离,每隔固定的工夫距离,反复的调用一个函数或指定的一段代码

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

参数阐明:
function: 每隔固定的间隔时间须要反复执行的函数
code[不举荐]: 每隔固定的工夫距离须要反复执行的一段代码
delay: 每次提早的毫秒数,函数的每次调用会在该提早之后产生。当参数值小于 10 的时候,会默认应用 10. 和 setTimeout 雷同,理论的延长时间可能会更长
arg1,…,argn[可选]: 附加参数,定时器到期后会作为参数传给函数

返回值:
返回值 timerId 是一个正整数,示意定时器的编号,能够传给clearInterval, 用来勾销定时器。

定时器应用的场景

反复执行 repeat
例如: 每个 10ms 输入一段指定的文字

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 秒内只能触发一次函数,屡次触发只会响应一次

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/
彻底弄懂函数防抖和函数节流

正文完
 0