need2nobasis
need2nobasis

Reputation: 139

Onclick button timeout javascript

Can someone help me get started with a button timeout feature. All I want is a button (when clicked) it becomes inactive for 2 seconds. After which it is active again.

Upvotes: 1

Views: 39391

Answers (4)

Web-E
Web-E

Reputation: 1189

You can use setTimeout() function in javascript. Something like

<html>
<head></head>
<body>

<input id="test" type="submit" value = "clickme" onclick="deactivatefunc()">
<script type="text/javascript">

 function deactivatefunc()
 {
    var btn = document.getElementById("test");
    btn.disabled = true;
    var mytimer = setTimeout(activate,2000);
 }

function  activate () {
    var btn = document.getElementById("test");
    btn.disabled = false;
}
</script>
</body> 

</html>

Upvotes: 0

Alex Turpin
Alex Turpin

Reputation: 47776

The function setTimeout allows you to specify a function to be called after an amount of milliseconds has passed. In this case, I passed in an anonymous function, that is, a function that does not have a name that is used for the sole purpose of re-enabling my button after 2 seconds.

var mybutton = document.getElementById("mybutton");
mybutton.onclick = function() {
    mybutton.disabled = true;
    setTimeout(function() {
        mybutton.disabled = false;
    }, 2000);
};​

Live example

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

Start of with:

<button>Click me!</button>

Add an event:

<button onClick="...">Click me!</button>

Now we need to put something in place of that ....

this can be used to mean "the button that was just clicked"

this.disabled can be set to true or false to disable (or re-enable) the button.

setTimeout(function() {...},2000); executes the anonymous function after two seconds have passed (or as near as the timer resolution allows).

Again, need to put something in the .... I've already told you how to re-enable the button.

Although, since this isn't terribly reliable inside anonymous functions, it's probably better to start with var t = this; and use t to mean the button.

With all that in place, you have:

<button onClick="var t = this; t.disabled = true; setTimeout(function() {t.disabled = false;},2000);">Click me!</button>

Done. I hope this explanation was helpful.

PS. To those who are against inline event handlers:

  1. This is an example
  2. The OP is a beginner
  3. An inline event is good enough

Upvotes: 2

gdoron
gdoron

Reputation: 150253

<input type="button" value="click" id="click" onclick="foo(this);"/>​

function foo(obj) {
    obj.disabled = true;
    setTimeout(function() {
        obj.disabled = false;
    }, 2000);
}​

LIVE DEMO

window.setTimeout on MDN:

Executes a code snippet or a function after specified delay.

Upvotes: 5

Related Questions