我用 JavaScript 開發了一個游戲,當時鐘指標移動得比平時稍微多一點時,用戶需要給出一個鍵輸入(按空格鍵)。目前,我正在使用一個setTimeout函式,讓用戶在時鐘指標走動(旋轉 10 度)后有 1 秒的時間進行按鍵輸入。如果用戶在時鐘指標比平時移動更多(15 度)時正確按下空格,則指示燈將閃爍綠色,否則將閃爍紅色。
我遇到的問題是,一旦用戶在手移動的 1 秒內給出輸入,指示器將不會閃爍,直到 1 秒過后(即,如果用戶在 0.4 秒后給出輸入,指示器將直到 0.6 以后才閃爍)
我知道這是因為指標是在我的setTimeout函式中設定的,它只會在 1 秒后執行代碼。我試圖測驗setTimeout函式之外的用戶輸入,但這樣用戶不會得到 1 秒的回應。
我想知道是否有辦法解決這個問題或更好的方法來解決這個問題?
//Get input after clock tick
setTimeout(() => {
if (irregular_tick && space_pressed) {
flashScreenGreen();
}
if (!(space_pressed) && irregular_tick) {
flashScreenRed();
}
},1000);
謝謝你的幫助!
uj5u.com熱心網友回復:
您需要在回呼之外保留對計時器的參考,setTimeout并為按鍵添加一個帶有中斷回呼的偵聽器,如果滿足所有條件,它將清除超時。
let timer = null;
let space_pressed = false;
function interruptHandler(e) {
spacebar_pressed = e.key === ' ';
if (timer !== null && irregular_tick && space_pressed) {
clearTimeout(timer);
timer = null;
space_pressed = false;
flashScreenGreen();
}
}
document.body.addEventListener('keyup', interruptHandler);
timer = setTimeout(() => {
if (!space_pressed && irregular_tick) {
flashScreenRed();
}
}, 1000);
uj5u.com熱心網友回復:
我認為 clearTimeout 函式會在這里幫助你
// Hold the reference to the timer
const timeoutId = setTimeout(() => {
if (irregular_tick && space_pressed) {
flashScreenGreen();
//You can use the clearTimeout function to end the timer
clearTimeout(timeoutId);
}
if (!(space_pressed) && irregular_tick) {
flashScreenRed();
//clear timeout, if you need it here too
clearTimeout(timeoutId);
}
},1000);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362448.html
標籤:javascript 项目
下一篇:減少回呼函式以從陣列中檢索屬性
