【學習】 防抖和節流

參考博客

https://blog.csdn.net/github_34708151/article/details/95165589

https://www.cnblogs.com/smallpen/p/10289050.html

https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/5

 

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

</head>

<body>

<div>

請輸入<input type="text" id ="input" style="border:1px solid #ccc">

</div>

<script>

// 防抖 防抖就是在出發後的一段時間內執行一次,例如:在進行搜索的時候,當用戶停止輸入後調用方法,節約請求資源

// 由此可以看出來,當我們重新頻繁的輸入後,並不會立即調用方法,只有在經過指定的間隔內沒有輸入的情況下才會調用函數方法;

// function writeWord (value) {

// console.log(value)

// }

// function deShake (fun,delay) {

// let timeFlag;

// return function (args) {

// var that = this

// clearTimeout(timeFlag);

// timeFlag = setTimeout (function () {

// fun.call(that,args)

// },delay)

// }

// }

// const deShakeInput = deShake(writeWord,1000)

// const inputAttribute = document.getElementById('input')

// inputAttribute.addEventListener('keyup',function(e){

// deShakeInput(e.target.value)

// })

 

//節流就是在頻繁觸發某個事件的情況下,每隔一段時間請求一次,類似打遊戲的時候長按某個按鍵,動作是有規律的在間隔時間觸發一次

function writeText(value) {

console.log(value)

}

 

function throttle (fn,delay) {

let canRun = true;

return function (arg) {

var that = this

if (!canRun) return;

canRun = false;

setTimeout (function () {

fn.call(that, arg);

canRun = true;

},delay)

}

}

const throttleInput = throttle(writeText,1000)

const inputId = document.getElementById('input')

inputId.addEventListener('keyup',function(e) {

throttleInput(e.target.value)

})

 

</script>

</body>

</html>

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