简体   繁体   中英

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!

document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
            count--;
            if(count>=0){
                id = document.getElementById("titolo");
                id.innerHTML = count;
            }
            if(count === 0){
                document.getElementById("titolo").style.display="none" ;
            }    
},1000);

setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.

Capture the return value of setInterval so that later you can use it to call clearInterval .

You should disable (or hide) the button (or other element) that the user can click to start the count down.

Make sure to always declare your variables with var , let or const .

Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent .

Here is how it could work:

 let start = document.getElementById("start"); let id = document.getElementById("titolo"); start.addEventListener("click", function () { start.disabled = true; id.style.display = "block"; id.textContent = "3"; let count = 3; let timer = setInterval(function(){ count--; id.textContent = count; if (count === 0) { id.style.display = "none" ; clearInterval(timer); start.disabled = false; } }, 1000); });
 <button id="start">Start</button> <div id="titolo"></div>

The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.

Example:

var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);

Example combined with your code:

 var intervalID, count, dom = document.querySelector("#titolo"); document.querySelector("#button").addEventListener("click", onClick); function onClick() { clearInterval(intervalID); dom.style.display = "block"; dom.textContent = 3; count = 3; intervalID = setInterval(function() { count -= 1; if (count >= 0) dom.textContent = count; else { dom.style.display = "none"; clearInterval(intervalID); } }, 1000); }
 <div id="titolo"></div> <button id="button">Button</button>

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