Shniper
Shniper

Reputation: 854

Progress bar with .delay

Fiddle I want to make a progress bar fill up 25% per second. My current code makes it go to 100% and stay there on click. I'm not sure if it's best to use jquery or css. Or if there is an easier way to do it. Also how can I make an action occur multiple times from one .click. Like you click battle and it hits the monster, then waits for the progress bar to fill, then hits the monster again and so on?

$('#battle').click(function() {
    $('#dam').html("You have hit the " + $('#monsters').val() + " for 5 damage");
  $('#bar').val(25).delay(1000);
  $('#bar').val(50).delay(1000);
  $('#bar').val(75).delay(1000);
  $('#bar').val(100);
});

Upvotes: 2

Views: 2050

Answers (1)

Anubhab
Anubhab

Reputation: 741

Here you go! https://jsfiddle.net/6nrjw0Le/

For your example I am using

setTimeout()

Your example edited.

var progress = function(sec){
    var interval = 250;//milliseconds
    setTimeout(function(){
    sec = sec+25;
        $('#bar').val(sec);
        if(sec < 100)
            progress(sec);//call self with new value
    },interval)
}

$('#battle').click(function() {
    $('#dam').html("You have hit the " + $('#monsters').val() + " for 5 damage");
  /*$('#bar').val(25).delay(1000);
  $('#bar').val(50).delay(1000);
  $('#bar').val(75).delay(1000);
  $('#bar').val(100);*/
  progress(0);//initialize progress bar
});

delay() is asynchronous. Putting one delay after another doesn't mean you get the execution after first one is complete.

Upvotes: 5

Related Questions