1

Trying to create a loading bar that gets slower and slower. I've made it so each bit of added width gets incrementally smaller, but now I want to do the same to the interval value. As of right now, my variable "itime" is set at 1000 and doesn't slow down with each step. What am I doing wrong?

var itime = 1000;

var progress = setInterval(function(){

    var insidewidth = $('#inside').width();

    if (insidewidth > 388) {
        $("body").css("background","blue");
        clearInterval(progress);
    }
    else {
        $("#inside").width($("#inside").width() + (175/insidewidth) );
        itime += 1000;
    };


}, itime);
Dustin Locke
  • 121
  • 1
  • 1
  • 6
  • Jquery already provides that - just use `animate()` with an appropriate easing function. – georg Oct 01 '13 at 22:32

3 Answers3

3

Once the interval is set, you can't just change it. Use a timeout and recursion instead :

var itime = 1000;

function progress(){
    setTimeout(function() {
        var insidewidth = $('#inside').width();

        if (insidewidth > 388) {
            $("body").css("background","blue");
        } else {
            $("#inside").width(insidewidth + (175/insidewidth) );
            itime += 1000;
            progress();
        }

    }, itime);
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

As you are using jQuery you may want to use easing functions, specifically easeOutExpo may fit your use-case e.g.

$("#inside").animate({ width: bar_width }, duration:5000, easing: 'easeOutExpo'});

if need be you can provide your custom easing function

Community
  • 1
  • 1
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
0

Here is another way to do it that does not involve repeatedly setting timers:

$(function() {
    var nMax = 99;
    var nWidth = 0;
    var nSpeed = 100;

    var $progressBar = $('.progress-bar div');

    var oInterval = window.setInterval(function() {
        nWidth += (nMax - nWidth) / 100;

        $progressBar.stop().animate({
            width: nWidth + '%'
        }, nSpeed);

        if(Math.round(nWidth) === nMax) window.clearInterval(oInterval);
    }, nSpeed);
});

Fiddle example

anarchocurious
  • 590
  • 6
  • 13
  • Does the job, but the client is asking that the bar moves, for example, after one second, then after two seconds, then after three seconds, etc. Ideas? – Dustin Locke Oct 11 '13 at 04:47