0
点赞
收藏
分享

微信扫一扫

window.requestAnimationFrame 封装与使用

8052cf60ff5c 2022-04-07 阅读 71
jsvue.js
<template>
	<div>
		adadadad
	</div>
</template>

<script>
// 这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
(function() {
	var lastTime = 0;
	var vendors = ['ms', 'moz', 'webkit', 'o'];
	for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
		window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
		window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
	}
 
	if (!window.requestAnimationFrame)
		window.requestAnimationFrame = function(callback, element) {
			var currTime = new Date().getTime();
			var timeToCall = Math.max(0, 16 - (currTime - lastTime));
			var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
				timeToCall);
			lastTime = currTime + timeToCall;
			return id;
		};
 
	if (!window.cancelAnimationFrame)
		window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());
export default {
	components: {},
	// 定义属性
	data() {
		return {
            time:null,
            elapsed:null,
            lastUpdate:null,
		}
	},
	// 计算属性,会监听依赖属性值随之变化
	computed: {
	},
	// 监控data中的数据变化
	watch: {},
	// 方法集合
	methods: {
		setnum:function(num){
            let _this = this;
            var now = new Date();
            var elapsed = now - _this.lastUpdate;
            if(elapsed >= 5000){
                console.log('每隔5000毫秒执行',elapsed);
                _this.lastUpdate = new Date();
                window.cancelAnimationFrame(_this.time);
                _this.time = window.requestAnimationFrame(_this.setnum);
            }else{
                _this.time = window.requestAnimationFrame(_this.setnum);
            }
        },
        
	},
    // 生命周期 - 创建完成(可以访问当前this实例)
  	created() {
        let _this = this;
        _this.lastUpdate = new Date();
        _this.setnum();
        // window.cancelAnimationFrame(_this.time)
  	},
	// 生命周期 - 挂载完成(可以访问DOM元素)
	mounted() {
    
	},
	beforeCreate() {}, // 生命周期 - 创建之前
	beforeMount() {}, // 生命周期 - 挂载之前
	beforeUpdate() {}, // 生命周期 - 更新之前
	updated() {}, // 生命周期 - 更新之后
	beforeDestroy() {}, // 生命周期 - 销毁之前
	destroyed() {}, // 生命周期 - 销毁完成
	activated() {}, // 如果页面有keep-alive缓存功能,这个函数会触发
}
</script>

<style lang='less' scoped>
  
</style>
举报

相关推荐

0 条评论