Skip to content

Instantly share code, notes, and snippets.

@pryley
Last active Sep 12, 2021
Embed
What would you like to do?
tiny-swiper plugin for breakpoints
import { SwiperInstance, SwiperPlugin } from '../core/index'
import { Options } from '../core/options'
export default <SwiperPlugin>function SwiperPluginBreakpoints (
instance: SwiperInstance,
options: Options,
) {
const isEnabled = Boolean(options.breakpoints)
if (!isEnabled) return
let timerId
let lastCallTime = 0
let wait = 200
const resizeListener = () => {
lastCallTime = Date.now()
if (timerId === undefined) {
timerId = startTimer(timerExpired)
}
}
const startTimer = (pendingFunc) => {
stopTimer()
return window.requestAnimationFrame(pendingFunc)
}
const stopTimer = () => {
window.cancelAnimationFrame(timerId)
timerId = undefined
}
const timerExpired = () => {
const timeSinceLastCall = Date.now() - lastCallTime
if (timeSinceLastCall >= wait || timeSinceLastCall < 0) {
stopTimer()
return updateSize()
}
timerId = startTimer(timerExpired)
}
const updateSize = () => {
for (const [breakpoint, values] of Object.entries(options.breakpoints)) {
if (instance.env.element.$el.offsetWidth >= +breakpoint) {
instance.options = Object.assign(instance.options, values)
}
}
instance.updateSize()
}
instance.on('after-init', () => {
window.addEventListener('resize', resizeListener, { passive: true })
window.requestAnimationFrame(updateSize)
})
instance.on('before-destroy', () => {
stopTimer()
window.removeEventListener('resize', resizeListener)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment