最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Slow down the speed of a for loop - Stack Overflow

programmeradmin1浏览0评论

I need to slow down the execution speed of for loop. I have to increase the width of the div slowly.

So far i have tried delay(),setTimeout(),setInterval() but without success. They all seem to behave in the same way.

HTML

<body>
   <h1>Hello</h1>
    <div class="divclass">

    </div>
</body>

jQuery

$(document).ready(function () {
    var width = $('.divclass').width();
    for (var i = 0; i < 6; i++) {
        width = width + 20;
        $('.divclass').delay(2000);
        $(".divclass").css("width", width);
    };
});

/

Can anyone show me where my mistake lies.

Thanks in advance.

I need to slow down the execution speed of for loop. I have to increase the width of the div slowly.

So far i have tried delay(),setTimeout(),setInterval() but without success. They all seem to behave in the same way.

HTML

<body>
   <h1>Hello</h1>
    <div class="divclass">

    </div>
</body>

jQuery

$(document).ready(function () {
    var width = $('.divclass').width();
    for (var i = 0; i < 6; i++) {
        width = width + 20;
        $('.divclass').delay(2000);
        $(".divclass").css("width", width);
    };
});

http://jsfiddle/RQVa8/1/

Can anyone show me where my mistake lies.

Thanks in advance.

Share Improve this question edited Oct 9, 2013 at 0:50 Tushar Gupta - curioustushar 57.1k24 gold badges106 silver badges109 bronze badges asked Aug 16, 2013 at 12:07 user1584103user1584103 1932 silver badges15 bronze badges 4
  • 2 Use animation instead of loop – closure Commented Aug 16, 2013 at 12:09
  • Have a look at setInterval(). jQuery's .delay() will only have an effect on the animation queue. – m90 Commented Aug 16, 2013 at 12:10
  • may be you r looking for animate – iJade Commented Aug 16, 2013 at 12:10
  • You can't slow down a for loop. – putvande Commented Aug 16, 2013 at 12:11
Add a ment  | 

2 Answers 2

Reset to default 6

DEMO

.animate() documentation

$(".divclass").animate({width: width}, 2000);

Use jQuery animate for this.

$(".divclass").animate({ "width": "+=20" }, 2000);

See the section about += to use relative values:

Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is puted by adding or subtracting the given number from the current value of the property.

发布评论

评论列表(0)

  1. 暂无评论