js

日期

1
2
3
4
# 前一月
new Date(new Date().setMonth(new Date().getMonth() -1 )).getFullYear() + '-' + (new Date(new Date().setMonth(new Date().getMonth() - 1)).getMonth() + 1)
# 前一天
new Date(new Date()-24*60*60*1000)

函数防抖

函数防抖(debounce):触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。

  • 实现方式:每次触发事件时设置一个延迟调用方法,并且取消之前的延时调用方法
  • 缺点:如果事件在规定的时间间隔内被不断的触发,则调用方法会被不断的延迟
1
2
3
4
5
6
7
8
9
10
11
12
13
function debounce (fn, wait){
var timer = null;
return function(){
if(timer !== null){
clearTimeout(timer);
}
timer = setTimeout(fn,wait);
}
}
function handle(){
console.log(Math.random());
}
window.addEventListener("scroll",debounce(handle,1000));

函数节流

函数节流(throttle):高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率。

  • 实现方式:每次触发事件时,如果当前有等待执行的延时函数,则直接return
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//节流throttle代码:
function throttle(fn,delay) {
let canRun = true; // 通过闭包保存一个标记
return function () {
// 在函数开头判断标记是否为true,不为true则return
if (!canRun) return;
// 立即设置为false
canRun = false;
// 将外部传入的函数的执行放在setTimeout中
setTimeout(() => {
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
// 当定时器没有执行的时候标记永远是false,在开头被return掉
fn.apply(this, arguments);
canRun = true;
}, delay);
};
}
function sayHi(e) {
console.log('节流:', e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi,500));

反转

‘1234567’.split(‘’).reverse().join(‘’)