節(jié)流與防抖
<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <meta http-equiv="X-UA-Compatible" content="IE=edge">
? ? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? ? <title>Document</title>
? ? <style>
? ? ? ? html,body{
? ? ? ? ? ? height: 500%;
? ? ? ? }
? ? </style>
</head>
<body>
? ? <button id="button">
? ? ? ? 按鈕
? ? </button>
? ? <!-- 節(jié)流與防抖 -->
? ? <script>
? ? ? ? // 節(jié)流:一個(gè)函數(shù)執(zhí)行一次后,只有大于設(shè)定的執(zhí)行周期才會(huì)執(zhí)行第二次
? ? ? ? function throttle(fn,delay){
? ? ? ? ? ? let lastTime = 0
? ? ? ? ? ? return function(){
? ? ? ? ? ? ? ? let nowTime = Date.now()
? ? ? ? ? ? ? ? if(nowTime - lastTime > delay){
? ? ? ? ? ? ? ? ? ? fn.call(this) ?//修正this指向問題
? ? ? ? ? ? ? ? ? ? lastTime = nowTime
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? document.onscroll=throttle(function(){
? ? ? ? ? ? console.log("scroll 時(shí)間被觸發(fā)了"+ Date.now())
? ? ? ? },2000)
? ? ? ?
? ? ? ? //防抖:一個(gè)需要頻繁觸發(fā)的函數(shù),在規(guī)定時(shí)間內(nèi)只讓最后一次生效,前面的不生效
? ? ? ? function debounce(fn,delay){
? ? ? ? ? ? let timer =null
? ? ? ? ? ? return function(){
? ? ? ? ? ? ? ? clearTimeout(timer)
? ? ? ? ? ? ? ? timer = setTimeout(function(){
? ? ? ? ? ? ? ? ? ? fn.apply(this)
? ? ? ? ? ? ? ? },delay)
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? document.getElementById("button").onclick = debounce(function(){
? ? ? ? ? ? console.log("點(diǎn)擊事件被觸發(fā)了"+Date.now())
? ? ? ? },500)
? ? ? ? // 節(jié)流進(jìn)階
? ? ? ? function debounce2(fn,delay,immediate){ ?//immediate為是否先執(zhí)行一次節(jié)流
? ? ? ? ? ? let timer=null
? ? ? ? ? ? return function(){
? ? ? ? ? ? ? ? clearTimeout(timer)
? ? ? ? ? ? ? ? if(immediate){
? ? ? ? ? ? ? ? ? ? let doOnce = !timer
? ? ? ? ? ? ? ? ? ? timer = setTimeout(function(){
? ? ? ? ? ? ? ? ? ? ? ? timer=null
? ? ? ? ? ? ? ? ? ? },delay)
? ? ? ? ? ? ? ? ? ? if(doOnce){
? ? ? ? ? ? ? ? ? ? ? ? fn.apply(this)
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? // 如果沒有設(shè)置第三個(gè)參數(shù),就是什么時(shí)候停止操作,之后delay時(shí)間才執(zhí)行
? ? ? ? ? ? ? ? ? ? timer = setTimeout(function(){
? ? ? ? ? ? ? ? ? ? ? ? fn.apply(this)
? ? ? ? ? ? ? ? ? ? },delay)
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? </script>
? ?
</body>
</html>