我正在使用 html 畫布制作游戲,我想在影片回圈中每次都檢查某些條件,如果該條件變為真一次,那么我不想檢查接下來的 3 秒,3 秒后我想再次檢查. 像
function animate(){
requestAnimationFrame(animate)
if (checking something){
if this if statement gets executed then don't check this if statement for next 3 seconds
}
這可能聽起來有點令人困惑,但無論如何都可以這樣做。
uj5u.com熱心網友回復:
如果你想在另一個方法中行內, setInterval 可能沒有幫助。
您可以只記下上次執行該檢查的時間(例如系統時間,以毫秒為單位),然后確保下次執行檢查時超過 3000 毫秒。
date.valueOf(); //An existing date object to milliseconds format
(new Date()).valueOf(); //current time in ms
你可以有兩個varslastCheckedTime和currentTime.
uj5u.com熱心網友回復:
requestAnimationFrame嘗試在下一幀上運行,而不是在三秒后運行。requestAnimationFrame 所以如果你想要三秒鐘就不要使用。
function animate(){
if (checking something){
setTimeout(animate, 3000);
} else {
requestAnimationFrame(animate);
}
}
uj5u.com熱心網友回復:
我的建議是添加一個標志 - 另一個可用于檢查是否應執行操作的變數,以及在一定時間后切換標志的另一個函式。
// THE CHECKING FLAG
let shouldCheckCondition = true;
function animate(){
requestAnimationFrame(animate)
// CHECK THE FLAG FIRST, IF SHOULD NOT CHECK, EXIT THE FUNCTION
if (!shouldCheckCondition) return;
if (condition){
// DISABLE THE CHECKING FLAG SO YOU SKIP THE SUBSEQUENT CHECKS
shouldCheckCondition = false;
// DO SOMETHING WHEN CONDITION IS MET AND CHECKING SHOULD BE DONE
// ENABLE THE CHECKING FLAG AFTER 3 second
setTimeout(() => { shouldCheckCondition = true; }, 3000);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458859.html
標籤:javascript html 帆布
