节流函数 只执行第一次
let timer = null
function throttle(fn, wait) {
return function() {
if (!timer) {
// 函数fn放在定时器外且定时器初始化放在throttle函数外 是只执行第一次;
// 函数fn放在定时器内且定时器初始化放在throttle函数内 是只执行最后一次
fn.apply(this, Array.prototype.slice.call(arguments, 0));
timer = setTimeout(() => {
timer = null;
}, wait);
}
}
}
节流函数 只执行最后一次
function throttle(fn, wait) {
let timer = null
return function() {
if (!timer) {
// 函数fn放在定时器外且定时器初始化放在throttle函数外 是只执行第一次;
// 函数fn放在定时器内且定时器初始化放在throttle函数内 是只执行最后一次
timer = setTimeout(() => {
fn.apply(this, Array.prototype.slice.call(arguments, 0));
timer = null;
}, wait);
}
}
}
监听鼠标滚轮事件 切换页面的轮播 (只执行第一次)
$(function () {
let index = 0;
let time = null
var timer = null
function startUp () {
time = setInterval(() => {
if (index < 4) {
index += 1
} else {
index = 0
}
swiper()
}, 6000);
}
swiper();
startUp();
function swiper() {
$('.swiper-slide').removeClass('active')
$('.swiper-slide').eq(index).addClass('active')
$('.pager-item').removeClass('active')
$('.pager-item').eq(index).addClass('active')
}
// 节流函数
function throttle(fn, wait) {
return function() {
if (!timer) {
// 函数fn放在定时器外且定时器初始化放在throttle函数外 是只执行第一次;
// 函数fn放在定时器内且定时器初始化放在throttle函数内 是只执行最后一次
fn.apply(this, Array.prototype.slice.call(arguments, 0));
timer = setTimeout(() => {
timer = null;
}, wait);
}
}
}
window.addEventListener('mousewheel', throttle((e) => {
e = e || window.event;
clearInterval(time);
if (e.wheelDelta) { //判断浏览器IE,谷歌滑轮事件
if (e.wheelDelta > 0) { //当滑轮向上滚动时
if (index === 0) {
index = 4
} else {
index -= 1
}
}
if (e.wheelDelta < 0) { //当滑轮向下滚动时
if (index < 4) {
index += 1
} else {
index = 0
}
}
} else if (e.detail) { //Firefox滑轮事件
if (e.detail> 0) { //当滑轮向上滚动时
if (index === 0) {
index = 4
} else {
index -= 1
}
}
if (e.detail< 0) { //当滑轮向下滚动时
if (index < 4) {
index += 1
} else {
index = 0
}
}
}
swiper();
startUp();
}, 2000))
})