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