最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

節(jié)流與防抖

2022-10-18 09:40 作者:對(duì)白淺淺  | 我要投稿

<!DOCTYPE html>

<html lang="en">

<head>

? ? <meta charset="UTF-8">

? ? <meta http-equiv="X-UA-Compatible" content="IE=edge">

? ? <meta name="viewport" content="width=device-width, initial-scale=1.0">

? ? <title>Document</title>

? ? <style>

? ? ? ? html,body{

? ? ? ? ? ? height: 500%;

? ? ? ? }

? ? </style>

</head>

<body>

? ? <button id="button">

? ? ? ? 按鈕

? ? </button>

? ? <!-- 節(jié)流與防抖 -->

? ? <script>

? ? ? ? // 節(jié)流:一個(gè)函數(shù)執(zhí)行一次后,只有大于設(shè)定的執(zhí)行周期才會(huì)執(zhí)行第二次

? ? ? ? function throttle(fn,delay){

? ? ? ? ? ? let lastTime = 0

? ? ? ? ? ? return function(){

? ? ? ? ? ? ? ? let nowTime = Date.now()

? ? ? ? ? ? ? ? if(nowTime - lastTime > delay){

? ? ? ? ? ? ? ? ? ? fn.call(this) ?//修正this指向問題

? ? ? ? ? ? ? ? ? ? lastTime = nowTime

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? document.onscroll=throttle(function(){

? ? ? ? ? ? console.log("scroll 時(shí)間被觸發(fā)了"+ Date.now())

? ? ? ? },2000)

? ? ? ?


? ? ? ? //防抖:一個(gè)需要頻繁觸發(fā)的函數(shù),在規(guī)定時(shí)間內(nèi)只讓最后一次生效,前面的不生效

? ? ? ? function debounce(fn,delay){

? ? ? ? ? ? let timer =null

? ? ? ? ? ? return function(){

? ? ? ? ? ? ? ? clearTimeout(timer)

? ? ? ? ? ? ? ? timer = setTimeout(function(){

? ? ? ? ? ? ? ? ? ? fn.apply(this)

? ? ? ? ? ? ? ? },delay)

? ? ? ? ? ? }

? ? ? ? }


? ? ? ? document.getElementById("button").onclick = debounce(function(){

? ? ? ? ? ? console.log("點(diǎn)擊事件被觸發(fā)了"+Date.now())

? ? ? ? },500)


? ? ? ? // 節(jié)流進(jìn)階

? ? ? ? function debounce2(fn,delay,immediate){ ?//immediate為是否先執(zhí)行一次節(jié)流

? ? ? ? ? ? let timer=null

? ? ? ? ? ? return function(){

? ? ? ? ? ? ? ? clearTimeout(timer)

? ? ? ? ? ? ? ? if(immediate){

? ? ? ? ? ? ? ? ? ? let doOnce = !timer

? ? ? ? ? ? ? ? ? ? timer = setTimeout(function(){

? ? ? ? ? ? ? ? ? ? ? ? timer=null

? ? ? ? ? ? ? ? ? ? },delay)

? ? ? ? ? ? ? ? ? ? if(doOnce){

? ? ? ? ? ? ? ? ? ? ? ? fn.apply(this)

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }else{

? ? ? ? ? ? ? ? ? ? // 如果沒有設(shè)置第三個(gè)參數(shù),就是什么時(shí)候停止操作,之后delay時(shí)間才執(zhí)行

? ? ? ? ? ? ? ? ? ? timer = setTimeout(function(){

? ? ? ? ? ? ? ? ? ? ? ? fn.apply(this)

? ? ? ? ? ? ? ? ? ? },delay)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }

? ? </script>

? ?

</body>

</html>


節(jié)流與防抖的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國(guó)家法律
九寨沟县| 思茅市| 赣州市| 西乌珠穆沁旗| 迁安市| 泰兴市| 隆回县| 永仁县| 轮台县| 镇原县| 新余市| 义乌市| 西丰县| 太谷县| 城步| 大荔县| 四川省| 桂林市| 广德县| 蓬溪县| 广丰县| 行唐县| 宣威市| 晋中市| 闽清县| 林口县| 新和县| 自治县| 湖南省| 家居| 浏阳市| 渝北区| 洪洞县| 咸宁市| 揭西县| 青龙| 昭苏县| 新建县| 镇远县| 平谷区| 上虞市|