Skip to content Skip to sidebar Skip to footer

Change Delay In Settimeout Using A Button Click

I am working on creating a 3D rotating cube in HTML canvas. My code looks something like this function rotateCubeZM() { fr = 5; stoppage = 1; for(let i = 0;i<200

Solution 1:

Do not use timers to change speed. The display rate of the device is fixed at 60 frames a second. You should animate in sync with this rate. Use requestAnimationFrame (rAF)

The code below uses rAF to update the animation once ever 60th second.

  • rotateSpeed is how much to rotate each frame
  • Each frame this speed is reduced by the amount in dacc. If below some min minSpeed the rotation is stopped;
  • A click event can change the rate of deceleration by changing dacc
  • rAF will stop when the rotate speed is below minSpeed.
  • To start the animation call startRotateAnim();

The values used are just an estimate of from your code. You will have to play with the values to get the animation to look how you want.

const fr = 5;  
const minSpeed = 0.01;
var rotateSpeed = 0, dacc;

// click event for quicker slowdown 
myButtonElement.addEventListener("click",() => dacc = 0.8);

// function to start / restart animationfunctionstartRotateAnim() { 
    const animRunning = rotateSpeed > minSpeed; // if animation running just change values   
    rotateSpeed = 1 * (1000/60) / fr; // rotate per frame
    dacc = 0.4;        // the bigger the number the quicker the slowdownif (!animRunning) {
        requestAnimationFrame(mainLoop); // start the animation.
    }
}

functionmainLoop() {  // this is called 60 times a secondif (rotateSpeed > minSpeed) {  rotateSpeed -= dacc }
    if (rotateSpeed > minSpeed) { 
        rotateCubeZ(rotateSpeed);
        requestAnimationFrame(mainLoop);
    }
}

Post a Comment for "Change Delay In Settimeout Using A Button Click"