LoginSignup
3
3

More than 5 years have passed since last update.

KONAMIコマンドを作る技術

Last updated at Posted at 2017-12-07

上上下下左右左右ba
はkeyCodeにすると

38 38 40 40 37 39 37 39 66 65

これを連続で押すと関数を実行させたい。
だが一定時間入力がない場合とKONAMIコマンド以外の入力はクリアにさせたい。

(() => {
    const KONAMI_PATTERN = "38384040373937396665"
    let input = ""
    let timeout = null
    document.addEventListener("keydown", (e) => {
        if(KONAMI_PATTERN.indexOf(e.keyCode) < 0) {
            clear()
            return
        }
        input += e.keyCode
        if (input == KONAMI_PATTERN) {
            called()
            clear()
        }
        clearTimeout(timeout)
        timeout = setTimeout(clear, 2000)
    })
    const clear = () => {
        input = ""
        clearTimeout(timeout)
    }

    const called = () => {
        // any operations
    }
})()

DEMO

また一つクソコードを書いてしまった。。。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3