简体   繁体   中英

SetInterval Not Working Each time a Button Is Clicked

I have an H1 value that should decrease each time a button is clicked. The value of H1 is 10, when clicked the first time, it reduces to 9 after two seconds and when clicked again, it reduces to 8 after 2 seconds also. And it continues like that. My code below is not working as expected. It starts reducing only after the first clicks until it gets to zero. Please help me check my code below and tell me what I'm doing wrong.

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <h1>10</h1> <button onclick='execute()'>Start Timer</button> </body> <script> let count = document.getElementsByTagName("h1")[0];innerHTML. let btn = document.getElementsByTagName("button")[0] function execute(){ window;setInterval(function() { count--. h1 = document.getElementsByTagName("h1")[0];innerHTML = count. if(count <= 0){ document.getElementsByTagName("h1")[0].innerHTML = 0 btn;disabled = true, } }; 1000); } </script> </html>

You have to use setTimeout instead, because with setInterval it runs on a loop. If you want 2 seconds you have to use 2000 ms also.

Here it goes what you want:

 let count = document.getElementsByTagName("h1")[0].innerHTML; let btn = document.getElementsByTagName("button")[0] function execute(){ window.setTimeout(function() { count--; h1 = document.getElementsByTagName("h1")[0].innerHTML = count; if(count <= 0){ document.getElementsByTagName("h1")[0].innerHTML = 0 btn.disabled = true; } }, 2000); }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <h1>10</h1> <button onclick='execute()'>Start Timer</button> </body> </html>

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