當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JavaScript 函数循环、延时、节流、防抖
生活随笔
收集整理的這篇文章主要介紹了
JavaScript 函数循环、延时、节流、防抖
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
函數(shù)循環(huán)(setInterval)
間隔指定的毫秒數(shù)不停地執(zhí)行指定的代碼
<button onclick="myStartFunction()">開始</button> <button onclick="myStopFunction()">停止</button><script> var myVar = null; //全局function myTimer(){var d=new Date();var t=d.toLocaleTimeString();document.getElementById("demo").innerHTML=t; }function myStart() {setInterval(function(){myTimer()},1000); // 開始執(zhí)行 }function myStopFunction(){clearInterval(myVar); // 停止執(zhí)行 } </script>函數(shù)延時(shí)(setTimeout)
在指定的毫秒數(shù)后執(zhí)行指定代碼
var myVar = null; //全局function myFunction() {myVar=setTimeout(function(){alert("Hello")},3000); }function myStopFunction() {clearTimeout(myVar); //停止執(zhí)行 }函數(shù)節(jié)流(throttle)
規(guī)定在一個(gè)單位時(shí)間內(nèi),只能觸發(fā)一次函數(shù)。如果這個(gè)單位時(shí)間內(nèi)觸發(fā)多次函數(shù),只有一次生效。
<button onclick="myFunction()">點(diǎn)擊</button> <script> // 節(jié)流函數(shù) function throttle(fun, delay) {let last, deferTimerreturn function (args) {let that = thislet _args = argumentslet now = +new Date()if (last && now < last + delay) {clearTimeout(deferTimer)deferTimer = setTimeout(function () {last = nowfun.apply(that, _args)}, delay)}else {last = nowfun.apply(that,_args)}} }function myFunction() {throttle(() => {...}, 1000) } </script> 高程中的經(jīng)典代碼: function throttle(method, context) {clearTimeout(method.tId);method.tId = setTimeout(function () {method.call(context);}, 100)}應(yīng)用場(chǎng)景:
1)鼠標(biāo)不斷點(diǎn)擊觸發(fā),mousedown(單位時(shí)間內(nèi)只觸發(fā)一次)
2)監(jiān)聽滾動(dòng)事件,比如是否滑到底部自動(dòng)加載更多,用throttle來判斷
3)視頻播放節(jié)點(diǎn)上報(bào)
函數(shù)防抖(debounce)
在事件被觸發(fā)n秒后再執(zhí)行回調(diào),如果在這n秒內(nèi)又被觸發(fā),則重新計(jì)時(shí)。
function debounce(fun, delay) {return function (args) {let that = thislet _args = argsclearTimeout(fun.id)fun.id = setTimeout(function () {fun.call(that, _args)}, delay)} }debounce(ajax, 500)應(yīng)用場(chǎng)景:
總結(jié)
以上是生活随笔為你收集整理的JavaScript 函数循环、延时、节流、防抖的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL中ALTER TABLE 语句
- 下一篇: Cocos2d-JS v3.0 alph