Search code examples
javascriptcountdown

Javascript countdown on first keyup


let userInput = document.getElementById('userInput');
const countdown = document.getElementById('countdown'); //DOM for change the html value
let countTime = 10;

userInput.addEventListener('keyup',function(){
    countdown.innerHTML = countTime;
    let mundur = setInterval(function(){
        countTime -= 1;
        if (countTime <= 0 ){
            clearInterval(mundur);
            countTime = 0;
        }
        countdown.innerHTML = countTime;
    },1000);
})

Please help me! I want to make a countdown when the user inputs, like https://10fastfingers.com . Countdown event will run on the first time keyup and not run again on next keyup. But in next keyup, the countdown not working properly. Please help me


Solution

  • You can tell the event listener to only fire once by adding an object to the third argument {once:true}

    addEventListener('keyup', function(){},{once:true})
    

    documentation to everything about event listeners: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

    Also, you should copy and paste your code, not an image. It makes it easier for people to potentially test or edit for you. Images of errors are acceptable and often easier to read IMO.