简体   繁体   中英

How to make a timer which doesnt start dircetly?

So i want to make a rubiks cube timer (example cstimer.net).
It's just like you hold space for a bit, you can release and start.
but if you press space and release instantly it wont start.
look at the website to understand what i mean.

but i dont understand how i can do it because i've tried some things but i cant figure it out!

this is what i would do but i dont know more

document.addEventListener("keydown", (e) => {
    if (e.keyCode === 32) {
        spacedown = true;
    }
})


document.addEventListener("keyup", (e) => {
    if (e.keyCode === 32) {
        spacedown = false;
    }
})```

I think I found it out, The code is something like this

let spacedown = false;
let spaceddown = false;
let ready = false;

document.addEventListener("keydown", (e) => {
    if (e.keyCode === 32) {
        spacedown = true;
        if (!spaceddown) {
            console.log('keydown & !spaceddown');
            start();
        }
        spaceddown = true;
    }
});

document.addEventListener("keyup", (e) => {
    if (e.keyCode === 32) {
        console.log('keyup');
        spacedown = false;
        spaceddown = false;
        start();
        ready = false;
    }
});

function start() {
    if (ready) {

        console.log('REadyyy'),
        timer.style.backgroundColor = 'white';
        startTimer();
        return
    }

    if (!spacedown) {

        console.log('not space'),
            timer.style.backgroundColor = 'white';
        return
    }

    setTimeout(() => {
        if (spacedown) {
            console.log('yellow');
            timer.style.backgroundColor = 'yellow';
        }
    }, 500)
    setTimeout(() => {
        if (spacedown) {
            console.log('red');
            timer.style.backgroundColor = 'red';
        }
    }, 1000)
    setTimeout(() => {
        if (spacedown) {
            ready = true;
            console.log('green');
            timer.style.backgroundColor = 'green';
        }
    }, 1500)
}

function startTimer(){
//your timer code
}```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM