2018-01-05

<!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>
<input type="text" id="test">
<script>
function debounce(fn, delay = 1000, time = 5000) {
let timer = null
let method = fn.bind(this)
let startTime = new Date()
return function (...args) {
let curTime = new Date()

    clearTimeout(timer)

    if (curTime - startTime >= time) {
      method(args)
      startTime = new Date()
    }
    timer = setTimeout(function () {
      method(args)
    }, delay)
  }
}

function search(val) { console.log('search', val) }

function onInput() {
  let value = test.value
  search(value)
}

let test = document.querySelector('#test')
test.oninput = debounce(onInput)

</script>
</body>

</html>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容