函数防抖和节流
Posted fazero
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了函数防抖和节流相关的知识,希望对你有一定的参考价值。
<!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>
<div id="btn">点我啊</div>
</body>
<script>
//每wait时间执行一次
function throttle(func, wait)
var timeout = null;
var previous = null;
return function ()
var now = +new Date();
var context = this;
if (!previous)
previous = now
//下次触发 func 剩余的时间
var remaining = wait - (now - previous);
// 如果小于0,说明离上次触发超过了wait时间,重新算
if (remaining < 0)
remaining = wait
if (!timeout)
timeout = setTimeout(() =>
previous = +new Date();
timeout = null;
func.apply(context, arguments)
, remaining);
;
////无论wait时间内执行多少次,只会在最后一次的wait时间后执行
function debounce(fn, wait)
var timeout = null;
return function ()
var context = this;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() =>
fn.apply(context, arguments)
, wait)
// function debounce(fn, wait, immediate)
// var timeout = null;
// var first = true;
// return function ()
// var context = this;
// if (immediate && first)
// fn.apply(context, arguments)
// first = false
//
// if (timeout) clearTimeout(timeout);
// timeout = setTimeout(() =>
// fn.apply(context, arguments)
// , wait)
//
//
function say()
var args = Array.prototype.slice.call(arguments)
console.log(new Date())
console.log('参数:', args.join(','))
var a = debounce(say, 3000, true)
document.getElementById('btn').onclick = () =>
a('hello', 'world')
</script>
</html>
以上是关于函数防抖和节流的主要内容,如果未能解决你的问题,请参考以下文章