防抖、節流、深拷貝
阿新 • • 發佈:2021-01-19
<script> // 防抖 以最後一次輸入為準 var request = function () { console.log(1234) } var debounce = function(fn,delaytime) { let timer return function() { clearTimeout(timer) timer = setTimeout(()=>{ fn.call(this) },delaytime) } } document.querySelector('.in').addEventListener('input',debounce(request,1000)) // 節流 規定時間內只讓第一次觸發生效,後面的不生效 var throttle = function(fn,delay) { var lasttime = 0 // 閉包防止每次呼叫lasttime都為0 return function() { var nowtime = new Date().getTime() if(nowtime - lasttime >delay){ fn.call(this) lasttime = nowtime } } } document.querySelector('.in').addEventListener('input',debounce(request,1000)) // 深拷貝 function deepClone(obj) { let cloneObj if(obj && typeof obj !== 'object'){ cloneObj = obj }if(obj && typeof obj == 'object') { cloneObj = Array.isArray(obj) ? []:{} } for (let key in obj){ if(obj.hasOwnProperty(key)) { if(obj[key] && typeof obj[key] == 'object') { cloneObj[key] = deepClone(obj[key]) }else{ cloneObj[key] = obj[key]; } } } return cloneObj } console.log(deepClone({ x: 1, y: [ 5, 6, 7 ], z: { a: 0, b: 1 } })) var obj = 1 var obj2 = obj obj2 = 2 console.log(obj2) console.log(obj) </script>