简体   繁体   中英

Automatically Enable/Disable a button

I have a button(for asking questions) and countdown timer(where time="2017/04/30 10:30:00), now what I want is when time=reaches 0 automatically disable a button and when time is >0 automatically enable the button again.

I have only one variable for saving date var time="2017/04/30". I guess constantly checking for time will be best option to make button enable/disable, but i do not know how to do it.

It's not a good practice to do this in one's front-end script as almost anyone with a basic JavaScript knowledge can re-enable the button when time==0 which I assume you don't want to happen.

I'll suggest doing this in one's server-side code. In brief:

  1. check timer when generating the page, if timer is out, generate the disabled button without any code that was supposed to handle the click event.
  2. check timer when handling the request triggered by the button click, return 404 or other error message if timer is out.

All that being said, if you "have to" do this quick dirty way, you can simply use a setInterval or setTimeout :

//javascript
// check timer every 200 ms
var TICK = 200; 
var checkTimerTask = setInterval(function(){
    if (getTimer() == 0){
        document.getElementById('buttonId').disabled = true; 
    } else {
        document.getElementById('buttonId').disabled = false;
    }
    // to stop checking uncomment the following line.
    // clearInterval(checkTimerTask);
}, TICK);

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