防抖
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <input id="search" type="text" /> <br /> <br /> <div id="content" style="background-color: darkgrey;width: auto;height: 50px;"></div> </body> <script type="text/javascript"> let num = 1; let content = document.getElementById("content"); function count(){ content.innerHTML = num++ ; } //content.onmousemove = count; //防抖debounce //输入完毕之后过1秒再查询(延迟执行) function debounce(func,wait){ let timeout; //定时器 return function(){ if(timeout){ clearTimeout(timeout); //取消之前的任务 } timeout = setTimeout(function(){ func.apply(this); //执行func函数 },wait) } } //输入完毕立即查询,过1秒之后才能再查询(立即执行) function debounce1(func,wait){ let timeout; //定时器 return function(){ if(timeout){ clearTimeout(timeout); //取消之前的任务 } let callNow = !timeout; //类型转化 timeout = setTimeout(()=>{ timeout = null; //清空当前定时器 },wait); if(callNow) func.apple(this); } } content.onmousemove = debounce(count,1000); </script> </html>