建一个 utils 文件夹 创建 utils.js 然后复制代码
//防止多次重复点击 (函数节流)
function throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) {
gapTime = 1000
}
let _lastTime = null
// 返回新的函数
return function (e) {
let _nowTime = + new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
// fn.apply(this, arguments) //将this和参数传给原函数
fn(this, e) //上方法不可行的解决办法 改变this和e
_lastTime = _nowTime
}
}
}
/*
*根据客户端的时间信息得到发表评论的时间格式
*多少分钟前,多少小时前,然后是昨天,然后再是月日
* Para :
* recordTime - {float} 时间戳
* yearsFlag -{bool} 是否要年份
*/
function getDiffTime(recordTime, yearsFlag) {
if (recordTime) {
recordTime = new Date(parseFloat(recordTime) * 1000);
var minute = 1000 * 60,
hour = minute * 60,
day = hour * 24,
now = new Date(),
diff = now - recordTime;
var result = '';
if (diff < 0) {
return result;
}
var weekR = diff / (7 * day);
var dayC = diff / day;
var hourC = diff / hour;
var minC = diff / minute;
if (weekR >= 1) {
var formate = 'MM-dd hh:mm';
if (yearsFlag) {
formate = 'yyyy-MM-dd hh:mm';
}
return recordTime.format(formate);
}
else if (dayC == 1 || (hourC < 24 && recordTime.getDate() != now.getDate())) {
result = '昨天' + recordTime.format('hh:mm');
return result;
}
else if (dayC > 1) {
var formate = 'MM-dd hh:mm';
if (yearsFlag) {
formate = 'yyyy-MM-dd hh:mm';
}
return recordTime.format(formate);
}
else if (hourC >= 1) {
result = parseInt(hourC) + '小时前';
return result;
}
else if (minC >= 1) {
result = parseInt(minC) + '分钟前';
return result;
} else {
result = '刚刚';
return result;
}
}
return '';
}
//导出
module.exports = {
getDiffTime: getDiffTime,
throttle: throttle,
}
接下来在需要的页面引入使用
var utils = require('../../utils/util.js'); //引入方法
tap: utils.throttle((that, e) => {
// base.reques 是自己封装的reques请求
base.request({
url: '',
type: "post",
sCallback: data => {
}
}
})
}, 5000//设置按钮在多长时间内点击只调用一次接口),