js-utils-v1
Version:
一组常用的 JavaScript 工具函数,包含时间格式化、图片下载、节流防抖等。
78 lines (59 loc) • 2.42 kB
Markdown
📌 一组常用的 JavaScript 工具函数,包含时间格式化、图片下载、节流防抖等。
---
```sh
npm install js-utils-v1
import { formatTime, Download, throttle, debounce, urlToBase64, validateFile } from "js-utils-v1";
// 时间格式化
console.log(formatTime(new Date())); // 2025-02-19 12:30:45
// 下载图片
Download("https://example.com/image.jpg");
// 节流
const throttledFunc = throttle(() => console.log("执行中..."), 1000);
throttledFunc();
// 防抖
const debouncedFunc = debounce(() => console.log("执行中..."), 500);
debouncedFunc();
// URL 转 Base64
urlToBase64("https://example.com/image.jpg").then(console.log);
// 图片校验
const file = new File(["content"], "image.jpg", { type: "image/jpeg" });
validateFile(file, 5);
```
1️⃣ 时间格式化 formatTime(dateString, M)
参数 | 类型 | 说明
-------- | ----- | -----
dateString | string&
M | string | 可选值:"month"(仅返回月日),"time"(仅返回时分)
返回值 | string | 格式化后的时间字符串,如 2025-02-19 12:30:45
2️⃣ 下载图片 Download(url)
参数 | 类型 | 说明
-------- | ----- | -----
url | string | 需要下载的图片地址
返回值 | void | 直接触发浏览器下载图片
3️⃣ 节流 throttle(func, delay)
参数 | 类型 | 说明
-------- | ----- | -----
func | function | 需要执行的函数
delay | number | 触发间隔(毫秒)
返回值 | function | 返回节流后的新函数
4️⃣ 防抖 debounce(func, wait, immediate)
参数 | 类型 | 说明
-------- | ----- | -----
func | function | 需要执行的函数
wait | number | 触发间隔(毫秒)
immediate | boolean | 是否立即执行
返回值 | function | 返回防抖后的新函数
5️⃣ URL 转 Base64 urlToBase64(url)
参数 | 类型 | 说明
-------- | ----- | -----
url | string | 需要转换的图片地址 图片的 URL
返回值 | Promise<string> | 返回 Promise,解析为 Base64 格式的图片数据
6️⃣ 图片校验 validateFile(file, size)
参数 | 类型 | 说明
-------- | ----- | -----
file | File | 需要校验的图片文件
size | number | 图片大小限制(MB)允许的最大大小(单位 MB)
返回值 | boolean | 校验成功返回 true,否则抛出错误