ant-design-vue/components/_util/getRequestAnimationFrame.ts

47 lines
1.4 KiB
TypeScript
Raw Normal View History

2019-01-12 03:33:27 +00:00
const availablePrefixs = ['moz', 'ms', 'webkit'];
2017-12-07 10:33:33 +00:00
2019-01-12 03:33:27 +00:00
function requestAnimationFramePolyfill() {
let lastTime = 0;
2021-06-23 15:08:16 +00:00
return function (callback) {
2019-01-12 03:33:27 +00:00
const currTime = new Date().getTime();
const timeToCall = Math.max(0, 16 - (currTime - lastTime));
2021-06-23 15:08:16 +00:00
const id = window.setTimeout(function () {
2019-01-12 03:33:27 +00:00
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
2017-12-07 10:33:33 +00:00
}
2019-01-12 03:33:27 +00:00
export default function getRequestAnimationFrame() {
2017-12-07 10:33:33 +00:00
if (typeof window === 'undefined') {
2019-01-12 03:33:27 +00:00
return () => {};
2017-12-07 10:33:33 +00:00
}
if (window.requestAnimationFrame) {
// https://github.com/vuejs/vue/issues/4465
2019-01-12 03:33:27 +00:00
return window.requestAnimationFrame.bind(window);
2017-12-07 10:33:33 +00:00
}
2019-01-12 03:33:27 +00:00
const prefix = availablePrefixs.filter(key => `${key}RequestAnimationFrame` in window)[0];
2017-12-07 10:33:33 +00:00
2019-01-12 03:33:27 +00:00
return prefix ? window[`${prefix}RequestAnimationFrame`] : requestAnimationFramePolyfill();
2017-12-07 10:33:33 +00:00
}
2019-01-12 03:33:27 +00:00
export function cancelRequestAnimationFrame(id) {
2017-12-07 10:33:33 +00:00
if (typeof window === 'undefined') {
2019-01-12 03:33:27 +00:00
return null;
2017-12-07 10:33:33 +00:00
}
if (window.cancelAnimationFrame) {
2019-01-12 03:33:27 +00:00
return window.cancelAnimationFrame(id);
2017-12-07 10:33:33 +00:00
}
2019-01-12 03:33:27 +00:00
const prefix = availablePrefixs.filter(
key => `${key}CancelAnimationFrame` in window || `${key}CancelRequestAnimationFrame` in window,
)[0];
2017-12-07 10:33:33 +00:00
return prefix
2019-01-12 03:33:27 +00:00
? (
window[`${prefix}CancelAnimationFrame`] || window[`${prefix}CancelRequestAnimationFrame`]
).call(this, id)
: clearTimeout(id);
2017-12-07 10:33:33 +00:00
}