函数节流和防抖动

来源:互联网 发布:ttrgb风扇软件控制 编辑:程序博客网 时间:2024/04/30 08:40
<!doctype html><html>    <head>        <meta charset="utf-8">        <title>赤壁之战</title>        <meta http-equiv="X-UA-Compatible" content="edge">        <meta name="viewport" content="width=device-width, initial-scale=1">        <meta name="Keywords" content="赤壁之战">        <meta name="description" content="赤壁之战">    </head><body><script>function throttle(func,wait,mustRun){    var timeout = null;    var startTime = new Date();    return function (){        var context = this,        args = arguments,        curTime = new Date();        clearTimeout(timeout);        if(curTime - startTime >= mustRun){            func.apply(context,args);            startTime = curTime;        }else{            timeout = setTimeout(func,wait);        }      }}function fn(){    console.log(1);}function fn2(){    console.log(2);}window.addEventListener('scroll',fn,false); window.addEventListener('scroll',throttle(fn2,500,1000),false);</script></body></html>


<!doctype html><html>    <head>        <meta charset="utf-8">        <title>赤壁之战</title>        <meta http-equiv="X-UA-Compatible" content="edge">        <meta name="viewport" content="width=device-width, initial-scale=1">        <meta name="Keywords" content="赤壁之战">        <meta name="description" content="赤壁之战">    </head><body><script>function debounce(fn,wait){    var timeout = null;    return function (){        clearTimeout(timeout);        timeout = setTimeout(fn,wait);    }}function debounce2 (fn,wait,immeditate){    var timeout = null;    return function (){        var context = this,        args = arguments;        var later = function (){            timeout = null;            if(!immeditate) fn.apply(context,args);        }        var callNow = immeditate & !timeout;        clearTimeout(timeout);        timeout = setTimeout(later,wait);        if(callNow) func.apply(context,args)    }}function fn(){    console.log(1);}function fn2(){    console.log(2);}window.addEventListener('scroll',fn,false); window.addEventListener('scroll',debounce2(fn2,500),false);</script>  </body></html>


0 0
原创粉丝点击