compUtils.ts
1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* 简单实现防抖方法
*
* 防抖(debounce)函数在第一次触发给定的函数时,不立即执行函数,而是给出一个期限值(delay),比如100ms。
* 如果100ms内再次执行函数,就重新开始计时,直到计时结束后再真正执行函数。
* 这样做的好处是如果短时间内大量触发同一事件,只会执行一次函数。
*
* @param fn 要防抖的函数
* @param delay 防抖的毫秒数
* @returns {Function}
*/
export function simpleDebounce(fn, delay = 100) {
let timer: any | null = null;
return function (...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
// @ts-ignore
fn.apply(this, args);
}, delay);
};
}
// /**
// * 日期格式化
// * @param date 日期
// * @param block 格式化字符串
// */
export function dateFormat(date, block) {
if (!date) {
return '';
}
let format = block || 'yyyy-MM-dd';
date = new Date(date);
const map = {
M: date.getMonth() + 1, // 月份
d: date.getDate(), // 日
h: date.getHours(), // 小时
m: date.getMinutes(), // 分
s: date.getSeconds(), // 秒
q: Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds(), // 毫秒
};
format = format.replace(/([yMdhmsqS])+/g, (all, t) => {
let v = map[t];
if (v !== undefined) {
if (all.length > 1) {
v = `0${v}`;
v = v.substr(v.length - 2);
}
return v;
} else if (t === 'y') {
return date
.getFullYear()
.toString()
.substr(4 - all.length);
}
return all;
});
return format;
}