防抖
一段时间只允许一件事情发生
应用场景: 在输入时间的input事件的时候,每输入一个字符,就会触发该事件。
**思想:**开启一个定时器,每过一段时间触发该事件,如果,还没到定时器规定的时间,又触发该事件,则清除之前的定时器。
var timer = null;
function debounce() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
dosomething...
},500)
}
防抖函数的封装(运用闭包)
function debounce(fn, wait=500) {
var timeout = null;
return function() {
if (timeout != null) {
clearTimeout(timeout);
}
timeout = setTimeout(() => fn(),wait);
}
}
运用
react中
<Form ref={this.formRef} onFieldsChange={this.fieldsChange()}>
// 表单发生改变
fieldsChange = () => debounce(() => {
this.props.setForm(this.formRef.current);
console.log(11111, this.formRef.current);
});
注意:这里必须要返回一个函数,不能如下直接调用,否则没有效果
<Form ref={this.formRef} onFieldsChange={this.fieldsChange}>
fieldsChange = () => debounce(() => {
this.props.setForm(this.formRef.current);
console.log(11111, this.formRef.current);
})();
节流
一段时间内,只处理一件事情(将多件事变成一件事)
思想: 通过一个变量来控制,在一段时间内,对该事件只做一次处理
function throttle(fn, wait) {
let value = true;
return function () {
if (!value) {
return false;
}
value = false;
setTimeout(() => {
fn();
value = true;
}, wait)
}
}
vue保存this的值
有些地方this的指向不是指向vue,则需要保存this的值
var self = null; //全局定义
self = this;
setStorageSync
setStorageSync(key,value);
这里的value需要是字符串,如果不是需要序列化
JSON.stringify(value)