节流
/**
* 节流函数
* @param func 要频繁执行的函数
* @param interval 执行函数的间隔时间 (ms)
* @param start func是马上频繁执行, 还是在interval ms后频繁执行
*/
function throttle(func, interval = 200, start = true) {
if (typeof func !== 'function') {
return console.error('请传入一个函数');
}
let timer = 0;
return function(...arg) {
let _this = this;
if (timer) {
return;
}
start && func.apply(_this, arg);
timer = setTimeout(() => {
(!start) && func.apply(_this, arg);
timer = 0;
}, interval);
}
}
window.onload = function(){
var obj = document.querySelector('#btn');
obj.addEventListener("click", throttle(() => {console.log('addEventListener')}, 2000, true));
}
防抖
/**
* @desc 函数防抖
* @param func 函数
* @param wait 延迟执行毫秒数
* @param immediate true 表立即执行,false 表非立即执行
*/
export function debounce(func, wait = 200, immediate = false) {
if (typeof func !== 'function') {
return console.error('请传入一个函数');
}
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callNow) func.apply(context, args);
} else {
timeout = setTimeout(function(){
func.apply(context, args);
}, wait);
}
}
}
是否在微信浏览器
/**
* 判断当前网页是否在微信浏览器中打开
* @returns {boolean}
*/
export function isWeChatBrowser() {
return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}
判断手机系统
/**
* 判断当前网页环境是 Android 还是 iOS
* @returns {{isAndroid: boolean, isIOS: boolean}}
*/
export function getPlatform() {
let userAgent = navigator.userAgent;
let isAndroid = userAgent.indexOf("Android") > -1 || userAgent.indexOf("Adr") > -1;
let isIOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
return {
isAndroid,
isIOS
}
}