- 获取随机占位图
export function getMockPic(w: number, h: number) {
return `https://picsum.photos/${w}/${h}?v=${Math.random()}`;
}
- 为空判断
export function isEmpty(value: any): boolean {
switch (typeof value) {
case 'undefined':
return true;
case 'string':
return (
value.trim() === '' ||
value === '' ||
value === 'undefined' ||
value === 'null'
);
case 'object': {
if (value instanceof Array) return value.length < 1;
else if (value instanceof Date) return false;
else if (value instanceof Object) return Object.keys(value).length < 1;
else return true;
}
default:
return false;
}
}
- 等待
export function waitBy(sec: number): Promise<any> {
let timed: any = undefined;
return new Promise(resolve => {
clearTimeout(timed);
timed = setTimeout(() => {
resolve(true);
clearTimeout(timed);
}, sec * 1000);
});
}
- 防抖与节流
export function debounce(fn: Function, wait: number): Function {
let timer: NodeJS.Timeout | null = null;
return function (this: any) {
let context = this;
let args = arguments;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function () {
fn.apply(context, args);
}, wait);
};
}
export function debounceAfter(fn: Function, wait: number): Function {
let timer: NodeJS.Timeout | null = null;
return function (this: any) {
let context = this;
let args = arguments;
if (timer) clearTimeout(timer);
let callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait);
if (callNow) fn.apply(context, args);
};
}
export function throttle(func: Function, wait: number, type: number): Function {
let previous = 0;
let timeout: NodeJS.Timeout | null = null;
return function (this: any) {
let context = this;
let args = arguments;
if (type === 1) {
let now = Date.now();
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
} else if (type === 2) {
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args);
}, wait);
}
}
};
}
- 震动手机
export function shakeIt(pattern: number | number[]) {
if (navigator && navigator.vibrate) {
navigator.vibrate(pattern);
}
}