首页 > 解决方案 > 速度控制一个 requestAnimationFrame 循环

问题描述

我有一个方法method2循环遍历一些数字,直到它到达末尾然后它重置。但是我需要控制它的速度。在另一种方法 ( method1) 中,我通过鼠标移动遍历这些数字,我使用以下方法控制此速度:

this.speedController += 1;
if (this.speedController < this.speed) {
    return;
}
if (this.speedController > this.speed) {
    this.speedController = 0;
}

我怎么能在我method2的 .

method2

spin(index) {
    let i = index;
    if (i >= this.images.length) {
        i = 1;
    }
    this.current = i;
    this.animationRequestID = window.requestAnimationFrame(() => this.spin(i));
    i += 1
},

编辑:

只是尝试使用超时,但是在停止动画时,我必须清除超时并运行clearAnimationFrame,这似乎是错误的。

spin(index) {
    window.setTimeout(() => {
        let i = index;
        if (i >= this.images.length) {
            i = 1;
        }
        this.current = i;
        this.animationRequestID = window.requestAnimationFrame(() => this.spin(i));
        i += 1
    }, this.speed * 10)
    
},

标签: javascript

解决方案


设法找到答案并使其适应我的需求,对于尝试此操作的其他任何人,请记住这是一个 Vue 组件。

export default {
    data() {
        return {
            spinStart: null,
            spinThen: Date.now(),
            fps: 1000 / 5
        };
    },
    created() {
        if (this.animation) {
            this.spinStart = this.spinThen;
            this.spin(1);
        }
    },
    methods: {
        spin(index) {
            let i = index;
            if (i >= this.images.length) {
                i = 1;
            }
            this.animationRequestID = window.requestAnimationFrame(() => this.spin(i));

            let now = Date.now();
            let elapsed = now - this.spinThen;

            if (elapsed > this.fps) {

                this.spinThen = now - (elapsed % this.fps);

                this.current = i;
                i += 1;
            }
        },

推荐阅读