簡體   English   中英

使用按鈕單擊更改 setTimeout 中的延遲

[英]Change delay in setTimeout using a button click

我正在努力在 HTML canvas 中創建一個 3D 旋轉立方體。 我的代碼看起來像這樣

function rotateCubeZM() {
    fr = 5;
    stoppage = 1;   
    for(let i = 0;i<200;i++,fr+=dacc) {
        setTimeout(rotateCubeZ,i*fr*stoppage,1);
    }
}

這里的 dacc 是一個減慢旋轉的減速因子。 我需要創建按鈕摩擦,這將進一步減慢 x 因子的減速。 如何在 setTimeout 仍在進行時更改減速因子? 我嘗試使用 onclick function 更新 dacc 的值,但這不起作用。 或者有沒有其他方法可以調用上述 function 來幫助解決這個問題?

謝謝您的幫助。

不要使用計時器來改變速度。 該設備的顯示速率固定為每秒 60 幀。 您應該與此速率同步動畫。 使用requestAnimationFrame (rAF)

下面的代碼使用 rAF 每 60 秒更新一次 animation。

  • rotateSpeed是每幀旋轉多少
  • 每一幀,這個速度都會減少dacc中的數量。 如果低於某個 min minSpeed則停止旋轉;
  • 點擊事件可以通過改變dacc來改變減速率
  • 當轉速低於 minSpeed 時,rAF 將停止。
  • 啟動 animation 調用startRotateAnim();

使用的值只是您的代碼的估計值。 您將不得不使用這些值來讓 animation 看起來像您想要的那樣。

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 animation
function startRotateAnim() { 
    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 slowdown
    if (!animRunning) {
        requestAnimationFrame(mainLoop); // start the animation.
    }
}

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

你不能那樣做。 您必須清除超時並設置新的超時。 setTimeout返回一個唯一標識符。

// timer holds the timer identifier.
let timer = setTimeout(function, 1000);

// clear it when you click the button
clearTimeout(timer);

// and set new timer with new value
timer = setTimeout(function, 2000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM