1. // 节流(一段时间执行一次之后,就不执行第二次)cd冷却
    2. function throttle(fn, delay){
    3. let canUse = true
    4. return function(){
    5. if(canUse){
    6. fn.apply(this, arguments)
    7. canUse = false
    8. setTimeout(()=>canUse = true, delay)
    9. }
    10. }
    11. }
    12. const throttled = throttle(()=>console.log('hi'))
    13. throttled()
    14. throttled()
    1. // 防抖(一段时间会等,然后带着一起做了)
    2. function debounce(fn, delay){
    3. let timerId = null
    4. return function(){
    5. const context = this
    6. if(timerId){window.clearTimeout(timerId)}
    7. timerId = setTimeout(()=>{
    8. fn.apply(context, arguments)
    9. timerId = null
    10. },delay)
    11. }
    12. }
    13. const debounced = debounce(()=>console.log('hi'))
    14. debounced()
    15. debounced()