-1

The idea of the script is to disable the button for 1500ms after if was pressed. Button press activate an animation of "loading bar". After 1500ms script should work again. The problem is that only setTimeout method doesn't work. Animation works well then button gets disabled, but after 1500ms it doesn't become enable.
Thankful for any help.

$(document).ready(function() {
    $('button').click(function(){                                  // <-- works fine 
        var width = Math.floor(Math.random() * (231 - 23) + 23);   // <-- works fine 
        $('.bar div').animate({width: width}, 1500);               // <-- works fine 
        $('.bar div span').text(Math.floor((width*100)/230) + '%');// <-- works fine 

        var intervalID = setInterval(function() {                  // <-- works fine 
            $('button').prop('disabled', true)}, 50);              // <-- works fine 
        setTimeout (function() {              // <-- this doesn't work
           clearInterval(intervalID)}, 1500); // <-- this doesn't work
    });
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Shouchy
  • 51
  • 1
  • 6
  • 4
    Well, it doesn't look like you enable the button anywhere. Simply clearing the interval doesn't enable the button. I'd also argue that the interval is unnecessary. Once you set the button to be disabled, it's disabled. You *explicitly* have to enable it again. – Felix Kling Aug 19 '14 at 15:30
  • 1
    You never set `disabled` to `false` anywhere! Your interval just keeps (re-)setting it to `true` (why are you doing this?). Stopping that interval won't magically make `disabled` `false`. – gen_Eric Aug 19 '14 at 15:30
  • Yes, i lack attention a little =) But thank you, any way. – Shouchy Aug 19 '14 at 15:42
  • @Shouchy: You're welcome. We're here to help :-) – gen_Eric Aug 19 '14 at 15:43

1 Answers1

1

The interval is not necessary. You just need to disable the button, set a timeout function and re-enable the button. Something like:

$("button").on("click", function(e) {
    var btn = $(this);

    var width = Math.floor(Math.random() * (231 - 23) + 23);
    $('.bar div').animate({width: width}, 1500);
    $('.bar div span').text(Math.floor((width*100)/230) + '%');

    btn.prop('disabled', true);
    setTimeout(function() {
        btn.prop('disabled', false);
    }, 1500);
});

Here is a JSFiddle

Corey
  • 5,818
  • 2
  • 24
  • 37