为什么第一次成功,然后func就是undefined了?节流怎么传递带参数的函数?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
html {
}
.t1 {
width: 500px;
height: 200px;
background: #0C9A9A;
}
</style>
</head>
<body>
<div>
<div class="t1">
按钮
</div>
</div>
<script>
function sayHi(data) {
console.log(data + new Date().getSeconds())
}
function throttle(func, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
console.log('timer == ')
if (!timer) {
timer = setTimeout(function() {
console.log('func == ', func)
func.apply(context, args);
timer = null;
}, delay);
}
}
}
window.addEventListener('resize', throttle(sayHi('abc'), 2000))
</script>
</body>
</html>
感谢楼下答疑
function sayHi(data) {
console.log(data + new Date().getSeconds())
}
function throttle(func, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
console.log('timer == ')
if (!timer) {
timer = setTimeout(function() {
console.log('func == ', func)
func.apply(context, args);
timer = null;
}, delay);
}
}
}
window.addEventListener('resize', throttle(function(){sayHi('abc')}, 2000))
throttle方法接收一个function,你这传入的是一个已经执行的方法,然后这个方法返回了undefined,就相当于你给throttle传入了undefined,改一下: