mparryy
mparryy

Reputation: 384

How to make this a slow jQuery counter

I am currently busy with making a new website. I would like to make a counter on my website that shows visitors how many websites I made. I am currently using Javascript and jQuery to do this. The only problem is that while using the for loop, the result shows very fast and I would like it to count up slowly. This is the code I have so far:

$(document).ready(function() {

    var websites = 10;
    for (var i=0;i<websites;i++)
    {
        $('.webcounter').html(i);
    }
});

Any one has an idea to making the counter go slow?

Upvotes: 0

Views: 2382

Answers (4)

SpYk3HH
SpYk3HH

Reputation: 22570

Just a quick guess, but try something like this (i'm at work and cant test myself, heheh)

var websites = 10, tmrSiteCount;

function siteCount(i) {
    if (i <= websites) {
        $('.webcounter').html(i);
        tmrSiteCount = setTimeout(function() { siteCount(i++); }, 1000);
    }
    else {
        clearTimeout(tmrSiteCount);
    };
}

$(document).ready(function() {
    tmrSiteCount = setTimeout(function() { siteCount(1); });
})

Upvotes: 1

Dan
Dan

Reputation: 12096

This timer works in seconds, you can put the code to run after it's complete in the else section:

Javascript

function countdown(count){

    $('.webcounter').html(count);

    count -= 1;

    if(count >= 0)
        setTimeout("countdown("+count+")", 1000);
    else
        alert("Countdown Complete");
}

$(document).ready(function() {

    countdown(10);
}

HTML

<div class="webcounter">Webcounter Holder</div>​

Demo

http://jsfiddle.net/silver89/SBXAQ/8/

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

You can try this:

var interval = window.setInterval(func, delay[, param1, param2, ...]);

Upvotes: 2

Chase
Chase

Reputation: 29549

Use setInterval:

EXAMPLE

HTML

​<div class="websites">0</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​

JQUERY

$(document).ready(function() {
    var websites = 10;
    var counter = 1;
    var id = setInterval(function(){ 
        $('.websites').text(counter);
        counter++;
        if(counter > websites){ clearInterval(id);}
    }, 500);    
});​

Upvotes: 1

Related Questions