存档,备用
// 节流:在一定时间内连续触发某事件,在这段时间段内只执行首次触发的那一次。
function throttleFunc(func, timeGap) {
if (timeGap==null || typeof(timeGap)=="undefined") {
timeGap = 2000 // 如果没有传递参数timeGap,或者该参数值为空,则使用默认值2000毫秒
}
let lastTime = null
return function () {
let currentTime = + new Date()
if (currentTime - lastTime > timeGap || !lastTime) {
console.log('exec', currentTime) // 正式环境可去掉
func.apply(this, arguments)
lastTime = currentTime
}else {
console.log('no exec') // 正式环境可去掉
}
}
}
// 格式化日期,示例:2021/12/01 12:12:01
const formatTime = 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(':')}`
}
// 格式化日期,示例:20211201121201
const formatTime2 = 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('')}`
}
// 格式化日期,示例:2021/12/01
const formatTime3 = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
return `${[year, month, day].map(formatNumber).join('-')}`
}
// 数字不足两位时,前面补0
const formatNumber = n => {
n = n.toString()
return n[1] ? n : `0${n}`
}
// 数字不足三位时,后面补0
const formatNumber2 = n => {
n = n.toString()
return n[2] ? n : n[1] ? `${n}0` : `${n}00`
}
// 格式化时间,格式化示例:05:00
const formatShowTime = number => {
let minute = Math.floor(number/60)
let second = Math.floor(number%60)
return `${[minute, second].map(formatNumber).join(':')}`
}
// 格式化时间,格式化示例:05:00.000
const formatShowMillisecond = number => {
let minute = Math.floor(Math.floor(number/1000)/60)
let second = Math.floor(Math.floor(number/1000)%60)
let millisecond = Math.floor(number%1000)
return `${[minute, second].map(formatNumber).join(':')}` + '.'+formatNumber2(millisecond)
}
module.exports = {
throttleFunc,
formatTime,
formatTime2,
formatTime3,
formatShowTime,
formatShowMillisecond,
}
网友评论