格式化时间
export const formatTime = (date: Date) => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return (
[year, month, day].map(formatNumber).join('/') +
' ' +
[hour, minute, second].map(formatNumber).join(':')
)
}
const formatNumber = (n: number) => {
const s = n.toString()
return s[1] ? s : '0' + s
}
计算2个日期之间相差多少天
export function dayDif(date1: Date, date2: Date): number {
return Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);
}
节流
export const throttle = (cb, wait = 3000) =>{
let previous = 0;
return function (...args) {
const nowDate = +new Date();
if( nowDate - previous > wait ){
previous = nowDate;
cb.apply(this, args);
}
}
}
防抖
export function debounce(cb, wait = 1000, immediate = false) {
let timeout;
return function(...args): void {
let callNow: boolean = immediate && !timeout;
if (timeout) clearTimeout(timeout);
timeout = setTimeout((): void => {
timeout = null;
if (!immediate) cb.apply(this, args);
}, wait);
if (callNow) cb.apply(this, args);
};
}