dzordz dzordz - 1 month ago 12
Javascript Question

jquery Add "random" stuff to value every second from current time?

I'm little. bit nooby about this. I've managed to get current time via javascript/jquery in my span tag. It is something to begin with to achieve my true intention.

I wanna have a script which adds certain number (between 0 and 5) every second in the time for 10 seconds (from the time I'm currently getting) to my current value in span class with

.value
class. Little bit confusing I know but I'll try to describe it in that way:

pressume that current time is
30/9/2013 - 10:38:47


and for ten seconds, function would add random values from range of 0 to 5

1st second - time: 30/9/2013 - 10:38:47 - adds: +3 - displays: 103
2nd second - time: 30/9/2013 - 10:38:48 - adds: +1 - displays: 104
3th second - time: 30/9/2013 - 10:38:49 - adds: +5 - displays: 109
4th second - time: 30/9/2013 - 10:38:50 - adds: +0 - displays: 109
5th second - time: 30/9/2013 - 10:38:51 - adds: +2 - displays: 111
6th second - time: 30/9/2013 - 10:38:52 - adds: +4 - displays: 115
...(up to)...
10th second - time: 30/9/2013 - 10:38:56 - adds: +2 - displays: 133

and now from beggining..


I have no idea how to do something like that, so I need some help, start point or something

Currently my project only have two spans and displaying current time: http://jsfiddle.net/a76wa/

html:

<span class="value">100</span>
</br>
<span class="new-time"></span>


script:

var currentdate = new Date();
var datetime = currentdate.getDate() + "/" + (currentdate.getMonth()+1) + "/" + currentdate.getFullYear() + " - " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();

$(".new-time").text(datetime);


any help or advice is appreciated.

Answer

I think this is what you are looking for: http://jsfiddle.net/jonigiuro/Q6wpu/

var startVal = $('.value');
var newTime = $('.new-time');
var startLink = $('.start');

startLink.on('click', function() {
    var tracker = 0; //varialbe to count the passed seconds
    var startValue = parseInt(startVal.text()); //get the start value
    var t = setInterval(function() {
        tracker++; //add 1 each second
        var randomNumber = Math.round(Math.random() * 10); //generate a random integer between 0 and 10
        startValue += randomNumber; //add the start value and the random number
        newTime.text(startValue); //change the text
        if(tracker === 10) { //after ten seconds
           clearInterval(t); //stop the timer
            startVal.text(startValue); //and change the start value
        }
    }, 1000);
});

You need to click on "start counter" to make it start