手動實現函數節流(throttle)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	/*
	* 函數節流
	* 簡單地講,就是讓一個函數無法在很短的時間間隔內連續調用,只有當上一次函數執行後過了你規定的時間間隔,、
	* 
    */
	<body>
		<script>
			function throttle(fn,incomingTime){
				let time=''
				return function(){
					let calculateTime= + new Date()
					if(calculateTime -time>incomingTime|| !time){
						fn()
						time=calculateTime
					}
				}
			}
			let fn=()=>{
				console.log("大哥好")
			}
			setInterval(throttle(fn,1000),1000)

       function throttle(fn) {
      let canRun = true; // 通過閉包保存一個標記
      return function () {
        if (!canRun) return; // 在函數開頭判斷標記是否爲true,不爲true則return
        canRun = false; // 立即設置爲false
        setTimeout(() => { // 將外部傳入的函數的執行放在setTimeout中
          fn.apply(this, arguments);
          // 最後在setTimeout執行完畢後再把標記設置爲true(關鍵)表示可以執行下一次循環了。
          //當定時器沒有執行的時                     候標記永遠是false,在開頭被return掉
          canRun = true;
        }, 500);
      };
    }
    function sayHi(e) {
      console.log(e.target.innerWidth, e.target.innerHeight);
    }
    window.addEventListener('resize', throttle(sayHi));

		</script>
	</body>
</html>

每一秒鐘打印一次 大哥好

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章