Solved

Jquery Random Number Counting

Posted on 2014-04-02
20
1,032 Views
Last Modified: 2014-04-07
I have a random number counting Jquery script where I need to pull numbers from my HTML and then change them randomly.

Right now my script is not changing the numbers, please help.

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>




<div style="display: inline;" id="WFItem467263">

<span class="wf-counter" style="display:  block !important;">

<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>

</span>

</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>




<span class="part_2" id="counter_2">100</span>




<script><!--

/* Calculate the initial number as of now */
	  var wf-counterq = $(".wf-counterq").text();
	  total = wf-counterq

	  /* Update every one second */
	  setInterval("UpdateCount_1()", 1000);

function UpdateCount_1() {
    /* Increment by a random number between 0 and 11 */
    total = total + Math.floor(Math.random() * 11);

    total = Math.round(total);

    /* Update the Counter 1 */
    var s = addCommas(total) + ' Count';
    $('#counter_1').html(s);
}

/* Calculate the initial number as of now */
	  var part_2 = $(".part_2").text();
	  total = part_2

	  /* Update every one second */
	  setInterval("UpdateCount_2()", 1000);

function UpdateCount_2() {
    /* Increment by random numbers 100 200 300 400 500 250 */
    total = total + Math.floor(Math.random(100 200 300 400 500 250));

    total = Math.round(total);

    /* Update the Counter 2 */
    var s = addCommas(total) + ' Count';
    $('#counter_2').html(s);
}

/* Commas */
function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

//--></script>

Open in new window

0
Comment
Question by:Richard Morris
  • 10
  • 10
20 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Some immediate issues that jump to mind

1. wf-counterq - variable names cannot contain dashes (-) - confuses the interpreter - interpreted as a minus

2. Random function canot take list of numbers
Rather put the numbers in an array and generate a random index into the array

Not sure what you are trying to acheive but here is some working code. Refer comments in bold.
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<div style="display: inline;" id="WFItem467263">
	<span class="wf-counter" style="display:  block !important;">
		<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>
	</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>




<span class="part_2" id="counter_2">100</span>




<script><!--
// ADD ARRAY OF VALUES TO RANDOMLY SELECT

var values = [100, 200, 300, 400, 500, 250];
/* Calculate the initial number as of now */

// FIX VARIABLE NAME - REMOVE DASH (-)
	  var wfcounterq = $(".wf-counterq").text();
	  total = wfcounterq

	  /* Update every one second */
	  setInterval("UpdateCount_1()", 1000);

function UpdateCount_1() {
    /* Increment by a random number between 0 and 11 */
    total = total + Math.floor(Math.random() * 11);

    total = Math.round(total);

    /* Update the Counter 1 */
    var s = addCommas(total) + ' Count';
    $('#counter_1').html(s);
}

/* Calculate the initial number as of now */
	  var part_2 = $(".part_2").text();
	  total = part_2

	  /* Update every one second */
	  setInterval("UpdateCount_2()", 1000);

function UpdateCount_2() {
    /* Increment by random numbers 100 200 300 400 500 250 */

// SELECT RANDOM VALUE USING INDEX INTO values ARRAY

    total = total + Math.floor(Math.random() * values.length + 1);

    total = Math.round(total);

    /* Update the Counter 2 */
    var s = addCommas(total) + ' Count';
    $('#counter_2').html(s);
}

/* Commas */
function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

//--></script>

Open in new window

0
 

Author Comment

by:Richard Morris
Comment Utility
@julianH

Counter 1 currently starts at 71 but when you load the page it overwrites the 71 and starts at 1,000 which is the wrong thing to do. Should start at 71 and then add a random number between 1 and 11.

Counter 2 currently starts at 100 but when you load the page it starts at 1,000 which is the wrong thing to do. It should start at 100. Also the random values appear to be from 1 to 11 however the random values for counter 2 are supposed to come from the string being 100 200 300 400 500 and 250.

Maybe my script needs a rewrite as it seems like too much code for just two simple actions to occur but I’m not sure how to shrink it so that it works.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
To take this forward I need to understand some things.

1. Not sure where the 71 comes from - counter_1 is a dash.
2. Why are you using a classes to access counters instead of id's.
3. Why are you using two different functions to update the counters.
4. First you set total to wfcounterq and then you overwrite this by setting it to part_2 - is this intentional.

In terms of how you described the problem - is this not what you want to do?
<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type="text/javascript">
var values = [100, 200, 300, 400, 500, 250];
var counter1 = 0, counter2 = 0;
$(function() {
	counter1 = parseInt($('#counter_1').text());
	counter2 = parseInt($('#counter_2').html());

	setInterval("UpdateCount()", 1000);
});

function UpdateCount()
{
	counter1 += Math.floor(Math.random() * 11);
	var s = addCommas(counter1) + ' Count';
	$('#counter_1').html(s);
	
	counter2 += values[Math.floor(Math.random() * values.length)];
	var s = addCommas(counter2) + ' Count';
	$('#counter_2').html(s);
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</script>
</head>
<body>
<span id="counter_1">71</span>
<span id="counter_2">100</span>
</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
Comment Utility
@julianH

1) The 71 comes from a different JavaScript that I cannot edit because it’s not hosted by me. This means I need the JavaScript to create a number which just so happens to be 71 at the moment, and then I need the script we’re working on now to change the 71 or whatever number happens to show up accordingly.

2) I think I should use id’s instead of classes, good catch.

3) I think I should be using one function to update the counters, good catch again.

4) wfcounterq and part_2 are separate counters but probably no longer needed since we're using id's now instead.

5) It appears you made the script work how I want it to work but you took the other JavaScript out that generates the number 71 which I need put back in for counter_1, please use missing code below:

<div style="display: inline;" id="WFItem467263">

<span class="wf-counter" style="display:  block !important;">

<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>

</span>

</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

Open in new window


6) I need setInterval to work separately for each counter.

7) I also need to be able to add more counters easily to this script (like copy and paste or minor edits) so if you could document out what each part of the script is doing for easy updating that would be very helpful.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
6) I need setInterval to work separately for each counter.

Why specifically do you need this - understanding will help give the correct solution.

Currently you have 2 setInterval's running both at 1sec intervals - as they will almost start at exactly the same time - why the need to have two?

The code should work by simply removing my <span>'s and adding your code

There is a timing issue with starting the first counter. Because you have to wait for the other javascript to popuplate the span - there needs to be delay before you start processing the increment otherwise you will read the value before it has been set.

Something like this. It might help to know what the other script is doing and whay you want to increment the counter. The solution below might not be optimal for what you are trying to achieve.

<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>




<div style="display: inline;" id="WFItem467263">

<span class="wf-counter" style="display:  block !important;">

<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>

</span>

</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<span class="part_2" id="counter_2">100</span>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>
<script type="text/javascript">
var values = [100, 200, 300, 400, 500, 250];
var counter1 = 0, counter2 = 0;
$(function() {
	setTimeout("start()", 2500);
});

function start()
{
	counter1 = parseInt($('#counter_1').html());
	
console.log(counter1);
	counter2 = parseInt($('#counter_2').html());

	setInterval("UpdateCount()", 1000);
}

function UpdateCount()
{
      // ADD RANDOM NUMBER TO counter1 (between 0 and 11)

	counter1 += Math.floor(Math.random() * 11);
	var s = addCommas(counter1) + ' Count';
	$('#counter_1').html(s);
	
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter2

	counter2 += values[Math.floor(Math.random() * values.length)];
	var s = addCommas(counter2) + ' Count';
	$('#counter_2').html(s);
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</script>

</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
Comment Utility
@julianH

6) I might want counter_1 to start at 2 second intervals and counter_2 to start at 4 second intervals for an example which means the counters should not share the same setInterval.

I understand the need for a delay for counter_1 because of the other JavaScript however why is there a delay for counter_2 because counter_2 should start immediately as intended which means the counters should not share the same setTimeout.

The counters are just for people to admire the numbers moving up, they serve no other purpose.

I found one bug in counter_2 which is when I set the value with a comma, example 48,000 the counter is unable to start at 48,000 as intended.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
I found one bug in counter_2 which is when I set the value with a comma, example 48,000 the counter is unable to start at 48,000 as intended.
It is not technically a bug - as there was nothing to specify that numbers with comma's are part of the input.

In terms of separate setIntervals - you can still achieve the same effect with counters.

Have a setInterval run every second and then use a mod on a counter to determine if it is time to update a particular counter i.e.
var count = 0;

function UpdateCounter()
{
   count++;
   if (count %2 == 0) {
      // update counter 1
   }
   if (count %4 == 0) {
     // update counter 2
   }
}

Open in new window

This will allow you to manage multiple counters operating at different intervals with one UpdateCounter function and one setInterval - much more manageable.

There is no reason for the delay on counter 2 other than that the delay is global - waits 2 seconds before getting the value for counter 1.

The counter2 code can come out of there and go into the $(function() { block.
0
 

Author Comment

by:Richard Morris
Comment Utility
1) Sorry, I have now added 48,000 to counter_2 but the three zeros after the comma are not being recognized by the counter, not sure what to do?

2) Tried to use separate intervals and doesn’t work, see code below.

3) I can’t find the $(function() { block for counter_2 to go so that it is not affected by the global timeout?

Also since only counter_1 requires a timeout, shouldn’t the timeout not be global and only specific to counter_1 so that it doesn’t affect the rest of the counters?

<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<span id="counter_2">48,000</span>

<script type="text/javascript">
var values = [100, 200, 300, 400, 500, 250];
var counter1 = 0, counter2 = 0;
$(function() {
	setTimeout("start()", 2500);
});

function start()
{
	counter1 = parseInt($('#counter_1').html());
	
	counter2 = parseInt($('#counter_2').html());

	setInterval("UpdateCount()", 1000);
}

function UpdateCount()
{
        // ADD RANDOM NUMBER TO counter1 (between 0 and 11)

	counter1 += Math.floor(Math.random() * 11);
	var s = addCommas(counter1) + ' Count';
	$('#counter_1').html(s);
	
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter2

	counter2 += values[Math.floor(Math.random() * values.length)];
	var s = addCommas(counter2) + ' Count';
	$('#counter_2').html(s);
}

var count = 0;

function UpdateCounter()
{
   count++;
   if (count %2 == 0) {
      // update counter 1
   }
   if (count %4 == 0) {
     // update counter 2
   }
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</script>

</body>
</html>

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
The code I posted earlier was meant as pseudo code to illustrate a point.

This should do what you want, handle the 48,000, single function procession with different intervals etc.
<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<span id="counter_2">48,000</span>

<script type="text/javascript">
var values = [100, 200, 300, 400, 500, 250];
var counter1 = 0, counter2 = 0;
var count = 0;
$(function() {
    // We drop the delay - the counter not being set will be handled in the 
    // functions getCounterValue and UpdateCount
    counter1 = getCounterValue('#counter_1');
    counter2 = getCounterValue('#counter_2');
    setInterval("UpdateCount()", 1000);
});

// Function to get a value from a counter if it exists or to return 0 
// if it does not
function getCounterValue(id)
{
    // use regular expression  replace to clean number of non-numeric chars
    val = parseInt($(id).html().replace(/[^0-9\.]+/g, ''));
    // if is NaN (not a number) then set to 0.
    if (isNaN(val)) {
        val = 0;
    }
    return val;
}
// Generic function for handling counters.
function UpdateCount()
{
    // The count variable is incremented everytime this function is run
    // i.e. every second. We use it to determine when to fire updates
    // on our various counters. This way we can do updates in a single 
    // function irrespective of how many counters we have
    
    count++;
    
    // what we are doing here is only firing the update if the 
    // count is a multiple of 2 (every 2 seconds)
    // in addition we are only firing if counter1 > 0 so only after
    // the counter1 delay has fired.
  
    if (counter1 == 0 ) {
        counter1 = getCounterValue('#counter_1');
    }
    
    if (counter1 > 0 && count % 2 == 0) {
        // ADD RANDOM NUMBER TO counter1 (between 0 and 11)
        counter1 += Math.floor(Math.random() * 11);
        var s = addCommas(counter1) + ' Count';
        $('#counter_1').html(s);
    }
    
    // No really necessary but shown for completeness.
    if (counter2 == 0 ) {
        counter2 = getCounterValue('#counter_2');
    }
    // here we are only firing every 4 seconds.
    if (count % 4 == 0) {
       // GET A RANDOM VALUE FROM THE values ARRAY and add to counter2
        counter2 += values[Math.floor(Math.random() * values.length)];
        var s = addCommas(counter2) + ' Count';
        $('#counter_2').html(s);
    }
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</script>

</body>
</html>

Open in new window

0
 

Author Comment

by:Richard Morris
Comment Utility
@julianH

Wow, your code works exactly the way I want it to, amazing work.

I added two more counters to make sure that I know how to work this script without any help in the future so can you please check to make sure I am working this script correctly?

Also, if I want two counters exactly the same, do I need to make two separate counters to do the same task or just use the same ID more than once? In a test, I tried to copy all four counters but only the first four counters work and the copies do not, what a strange phenomena, is this normal behavior?

<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<span id="counter_2">48,000</span>
<br>
<span id="counter_3">16,000</span>
<br>
<span id="counter_4">1</span>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<span id="counter_2">48,000</span>
<br>
<span id="counter_3">16,000</span>
<br>
<span id="counter_4">1</span>

<script type="text/javascript">
var values1 = [100, 200, 300, 400, 500, 234];
var values2 = [7, 12, 18, 22, 28, 39];
var counter1 = 0, counter2 = 0, counter3 = 0, counter4 = 0;
var count = 0;
$(function() {
    // We drop the delay - the counter not being set will be handled in the 
    // functions getCounterValue and UpdateCount
    counter1 = getCounterValue('#counter_1');
    counter2 = getCounterValue('#counter_2');
    counter3 = getCounterValue('#counter_3');
    counter4 = getCounterValue('#counter_4');
    setInterval("UpdateCount()", 1000);
});

// Function to get a value from a counter if it exists or to return 0 
// if it does not
function getCounterValue(id)
{
    // use regular expression  replace to clean number of non-numeric chars
    val = parseInt($(id).html().replace(/[^0-9\.]+/g, ''));
    // if is NaN (not a number) then set to 0.
    if (isNaN(val)) {
        val = 0;
    }
    return val;
}
// Generic function for handling counters.
function UpdateCount()
{
    // The count variable is incremented everytime this function is run
    // i.e. every second. We use it to determine when to fire updates
    // on our various counters. This way we can do updates in a single 
    // function irrespective of how many counters we have
    
    count++;
    
    // what we are doing here is only firing the update if the 
    // count is a multiple of 2 (every 2 seconds)
    // in addition we are only firing if counter1 > 0 so only after
    // the counter1 delay has fired.
  
    if (counter1 == 0 ) {
        counter1 = getCounterValue('#counter_1');
    }
    
    if (counter1 > 0 && count % 2 == 0) {
        // ADD RANDOM NUMBER TO counter1 (between 0 and 11)
        counter1 += Math.floor(Math.random() * 11);
        var s = addCommas(counter1) + ' Count';
        $('#counter_1').html(s);
    }
    
    // No really necessary but shown for completeness.
    if (counter2 == 0 ) {
        counter2 = getCounterValue('#counter_2');
    }
    // here we are only firing every 4 seconds.
    if (count % 4 == 0) {
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter2
        counter2 += values1[Math.floor(Math.random() * values1.length)];
        var s = addCommas(counter2) + ' Count';
        $('#counter_2').html(s);
    }

    // No really necessary but shown for completeness.
    if (counter3 == 0 ) {
        counter3 = getCounterValue('#counter_3');
    }
    // here we are only firing every 6 seconds.
    if (count % 6 == 0) {
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter3
        counter3 += values2[Math.floor(Math.random() * values2.length)];
        var s = addCommas(counter3) + ' Count';
        $('#counter_3').html(s);
    }

    // No really necessary but shown for completeness.
    if (counter4 == 0 ) {
        counter4 = getCounterValue('#counter_4');
    }
    // here we are only firing every 1 second.
    if (count % 1 == 0) {
        // ADD RANDOM NUMBER TO counter4 (between 1 and 3)
        counter4 += 1 + Math.floor(Math.random() * 3);
        var s = addCommas(counter4);
        $('#counter_4').html(s);
    }
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</script>

</body>
</html>

Open in new window

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
A couple of things

Testing for count % 1 is not necessary as this will always return true - if you want the counter to execute every second then simply put the code into the UpdateCount without a surrounding if statement.

With respect to using the same ID for more than one counter - no - don't do that. ID's must be unique. It would be possible to use a class - but that would require modification to the code - I would just go with what you have.
0
 

Author Comment

by:Richard Morris
Comment Utility
Does it hurt the script to test for count % 1 because if not I’ll leave it in so that if I need to change it to % 2 for an example it will be ready for me.

I now have a problem, I need counter 1 and counter 5 to match but they are now out of sync.

<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<span id="counter_2">48,000</span>
<br>
<span id="counter_3">16,000</span>
<br>
<span id="counter_4">1</span>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_5">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<script type="text/javascript">
var values1 = [100, 200, 300, 400, 500, 234];
var values2 = [7, 12, 18, 22, 28, 39];
var counter1 = 0, counter2 = 0, counter3 = 0, counter4 = 0, counter5 = 0;
var count = 0;
$(function() {
    // We drop the delay - the counter not being set will be handled in the 
    // functions getCounterValue and UpdateCount
    counter1 = getCounterValue('#counter_1');
    counter2 = getCounterValue('#counter_2');
    counter3 = getCounterValue('#counter_3');
    counter4 = getCounterValue('#counter_4');
    counter5 = getCounterValue('#counter_5');
    setInterval("UpdateCount()", 1000);
});

// Function to get a value from a counter if it exists or to return 0 
// if it does not
function getCounterValue(id)
{
    // use regular expression  replace to clean number of non-numeric chars
    val = parseInt($(id).html().replace(/[^0-9\.]+/g, ''));
    // if is NaN (not a number) then set to 0.
    if (isNaN(val)) {
        val = 0;
    }
    return val;
}
// Generic function for handling counters.
function UpdateCount()
{
    // The count variable is incremented everytime this function is run
    // i.e. every second. We use it to determine when to fire updates
    // on our various counters. This way we can do updates in a single 
    // function irrespective of how many counters we have
    
    count++;
    
    // what we are doing here is only firing the update if the 
    // count is a multiple of 2 (every 2 seconds)
    // in addition we are only firing if counter1 > 0 so only after
    // the counter1 delay has fired.
  
    if (counter1 == 0 ) {
        counter1 = getCounterValue('#counter_1');
    }
    
    if (counter1 > 0 && count % 2 == 0) {
        // ADD RANDOM NUMBER TO counter1 (between 0 and 11)
        counter1 += Math.floor(Math.random() * 11);
        var s = addCommas(counter1) + ' Count';
        $('#counter_1').html(s);
    }
    
    // No really necessary but shown for completeness.
    if (counter2 == 0 ) {
        counter2 = getCounterValue('#counter_2');
    }
    // here we are only firing every 4 seconds.
    if (count % 4 == 0) {
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter2
        counter2 += values1[Math.floor(Math.random() * values1.length)];
        var s = addCommas(counter2) + ' Count';
        $('#counter_2').html(s);
    }

    // No really necessary but shown for completeness.
    if (counter3 == 0 ) {
        counter3 = getCounterValue('#counter_3');
    }
    // here we are only firing every 6 seconds.
    if (count % 6 == 0) {
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter3
        counter3 += values2[Math.floor(Math.random() * values2.length)];
        var s = addCommas(counter3) + ' Count';
        $('#counter_3').html(s);
    }

    // No really necessary but shown for completeness.
    if (counter4 == 0 ) {
        counter4 = getCounterValue('#counter_4');
    }
    // here we are only firing every 1 second.
    if (count % 1 == 0) {
        // ADD RANDOM NUMBER TO counter4 (between 1 and 3)
        counter4 += 1 + Math.floor(Math.random() * 3);
        var s = addCommas(counter4);
        $('#counter_4').html(s);
    }

    if (counter5 == 0 ) {
        counter5 = getCounterValue('#counter_5');
    }
    
    if (counter5 > 0 && count % 2 == 0) {
        // ADD RANDOM NUMBER TO counter1 (between 0 and 11)
        counter5 += Math.floor(Math.random() * 11);
        var s = addCommas(counter5) + ' Count';
        $('#counter_5').html(s);
    }
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</script>

</body>
</html>

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
No it does not matter if you include the count % 1

For counters that must be in synch just put the update in the same block of code i.e. don't create a spearate block for counter5 just make counter 1 do this.
If both counters must show same value then
    if (count % 2 == 0) {
        // ADD RANDOM NUMBER TO counter1 (between 0 and 11)
        counter1 += Math.floor(Math.random() * 11);
        var s = addCommas(counter1) + ' Count';
        if (counter1 > 0) {
           $('#counter_1').html(s);
        }
        if (counter5 > 0) {
           $('#counter_5').html(s);
        }
    }
 

Open in new window

If managing separately
    if (count % 2 == 0) {
        // ADD RANDOM NUMBER TO counter1 (between 0 and 11)
        if (counter1 > 0) {
           counter1 += Math.floor(Math.random() * 11);
           var s = addCommas(counter1) + ' Count';
           $('#counter_1').html(s);
        }
        if (counter5 > 0) {
           counter5 += Math.floor(Math.random() * 11);
           var s = addCommas(counter5) + ' Count';
           $('#counter_5').html(s);
        }
    }
 

Open in new window

0
 

Author Comment

by:Richard Morris
Comment Utility
Yes, counter 1 and counter 5 must show the same value which you'll see I did below, are there any further optimizations we can do to the code?

<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<span id="counter_2">48,000</span>
<br>
<span id="counter_3">16,000</span>
<br>
<span id="counter_4">1</span>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_5">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<script type="text/javascript">
var values1 = [100, 200, 300, 400, 500, 234];
var values2 = [7, 12, 18, 22, 28, 39];
var counter1 = 0, counter2 = 0, counter3 = 0, counter4 = 0, counter5 = 0;
var count = 0;
$(function() {
    // We drop the delay - the counter not being set will be handled in the 
    // functions getCounterValue and UpdateCount
    counter1 = getCounterValue('#counter_1');
    counter2 = getCounterValue('#counter_2');
    counter3 = getCounterValue('#counter_3');
    counter4 = getCounterValue('#counter_4');
    counter5 = getCounterValue('#counter_5');
    setInterval("UpdateCount()", 1000);
});

// Function to get a value from a counter if it exists or to return 0 
// if it does not
function getCounterValue(id)
{
    // use regular expression  replace to clean number of non-numeric chars
    val = parseInt($(id).html().replace(/[^0-9\.]+/g, ''));
    // if is NaN (not a number) then set to 0.
    if (isNaN(val)) {
        val = 0;
    }
    return val;
}
// Generic function for handling counters.
function UpdateCount()
{
    // The count variable is incremented everytime this function is run
    // i.e. every second. We use it to determine when to fire updates
    // on our various counters. This way we can do updates in a single 
    // function irrespective of how many counters we have
    
    count++;
    
    // what we are doing here is only firing the update if the 
    // count is a multiple of 2 (every 2 seconds)
    // in addition we are only firing if counter1 > 0 so only after
    // the counter1 delay has fired.
  
    if (counter1 == 0 ) {
        counter1 = getCounterValue('#counter_1');
    }
    
    if (counter5 == 0 ) {
        counter5 = getCounterValue('#counter_5');
    }
    
    if (count % 2 == 0) {
        // ADD RANDOM NUMBER TO counter1 (between 0 and 11)
        counter1 += Math.floor(Math.random() * 11);
        var s = addCommas(counter1) + ' Count';
        if (counter1 > 0) {
           $('#counter_1').html(s);
        }
        if (counter5 > 0) {
           $('#counter_5').html(s);
        }
    }
    
    // No really necessary but shown for completeness.
    if (counter2 == 0 ) {
        counter2 = getCounterValue('#counter_2');
    }
    // here we are only firing every 4 seconds.
    if (count % 4 == 0) {
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter2
        counter2 += values1[Math.floor(Math.random() * values1.length)];
        var s = addCommas(counter2) + ' Count';
        $('#counter_2').html(s);
    }

    // No really necessary but shown for completeness.
    if (counter3 == 0 ) {
        counter3 = getCounterValue('#counter_3');
    }
    // here we are only firing every 6 seconds.
    if (count % 6 == 0) {
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter3
        counter3 += values2[Math.floor(Math.random() * values2.length)];
        var s = addCommas(counter3) + ' Count';
        $('#counter_3').html(s);
    }

    // No really necessary but shown for completeness.
    if (counter4 == 0 ) {
        counter4 = getCounterValue('#counter_4');
    }
    // here we are only firing every 1 second.
    if (count % 1 == 0) {
        // ADD RANDOM NUMBER TO counter4 (between 1 and 3)
        counter4 += 1 + Math.floor(Math.random() * 3);
        var s = addCommas(counter4);
        $('#counter_4').html(s);
    }
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</script>

</body>
</html>

Open in new window


Also, if count % 2 represents 2 seconds, what would represent 2 minutes, 120 perhaps?
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
"are there any further optimizations we can do to the code?"
Probably - but that is outside the scope of the original question.
0
 

Author Comment

by:Richard Morris
Comment Utility
Understood.

Did I add the block of code correctly because I had to add some extra to get it to work, not sure if I did that right or not?

<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_1">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<span id="counter_2">48,000</span>
<br>
<span id="counter_3">16,000</span>
<br>
<span id="counter_4">1</span>

<div style="display: inline;" id="WFItem467263">
<span class="wf-counter" style="display:  block !important;">
<span name="https://app.getresponse.com/display_subscribers_count.js?campaign_name=arkiq&var=0" class="wf-counterq" id="counter_5">-</span>
</span>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=467263&mg_param1=1&u=B49N"></script>

<script type="text/javascript">
var values1 = [100, 200, 300, 400, 500, 234];
var values2 = [7, 12, 18, 22, 28, 39];
var counter1 = 0, counter2 = 0, counter3 = 0, counter4 = 0, counter5 = 0;
var count = 0;
$(function() {
    // We drop the delay - the counter not being set will be handled in the 
    // functions getCounterValue and UpdateCount
    counter1 = getCounterValue('#counter_1');
    counter2 = getCounterValue('#counter_2');
    counter3 = getCounterValue('#counter_3');
    counter4 = getCounterValue('#counter_4');
    counter5 = getCounterValue('#counter_5');
    setInterval("UpdateCount()", 1000);
});

// Function to get a value from a counter if it exists or to return 0 
// if it does not
function getCounterValue(id)
{
    // use regular expression  replace to clean number of non-numeric chars
    val = parseInt($(id).html().replace(/[^0-9\.]+/g, ''));
    // if is NaN (not a number) then set to 0.
    if (isNaN(val)) {
        val = 0;
    }
    return val;
}
// Generic function for handling counters.
function UpdateCount()
{
    // The count variable is incremented everytime this function is run
    // i.e. every second. We use it to determine when to fire updates
    // on our various counters. This way we can do updates in a single 
    // function irrespective of how many counters we have
    
    count++;
    
    // what we are doing here is only firing the update if the 
    // count is a multiple of 2 (every 2 seconds)
    // in addition we are only firing if counter1 > 0 so only after
    // the counter1 delay has fired.
  
    if (counter1 == 0 ) {
        counter1 = getCounterValue('#counter_1');
    }
    
    if (counter5 == 0 ) {
        counter5 = getCounterValue('#counter_5');
    }
    
    if (count % 2 == 0) {
        // ADD RANDOM NUMBER TO counter1 (between 0 and 11)
        counter1 += Math.floor(Math.random() * 11);
        var s = addCommas(counter1) + ' Count';
        if (counter1 > 0) {
           $('#counter_1').html(s);
        }
        if (counter5 > 0) {
           $('#counter_5').html(s);
        }
    }
    
    // No really necessary but shown for completeness.
    if (counter2 == 0 ) {
        counter2 = getCounterValue('#counter_2');
    }
    // here we are only firing every 4 seconds.
    if (count % 4 == 0) {
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter2
        counter2 += values1[Math.floor(Math.random() * values1.length)];
        var s = addCommas(counter2) + ' Count';
        $('#counter_2').html(s);
    }

    // No really necessary but shown for completeness.
    if (counter3 == 0 ) {
        counter3 = getCounterValue('#counter_3');
    }
    // here we are only firing every 6 seconds.
    if (count % 6 == 0) {
        // GET A RANDOM VALUE FROM THE values ARRAY and add to counter3
        counter3 += values2[Math.floor(Math.random() * values2.length)];
        var s = addCommas(counter3) + ' Count';
        $('#counter_3').html(s);
    }

    // No really necessary but shown for completeness.
    if (counter4 == 0 ) {
        counter4 = getCounterValue('#counter_4');
    }
    // here we are only firing every 1 second.
    if (count % 1 == 0) {
        // ADD RANDOM NUMBER TO counter4 (between 1 and 3)
        counter4 += 1 + Math.floor(Math.random() * 3);
        var s = addCommas(counter4);
        $('#counter_4').html(s);
    }
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</script>

</body>
</html>

Open in new window

0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
Comment Utility
Looks correct.
0
 

Author Closing Comment

by:Richard Morris
Comment Utility
@julianH is an awesome coder who really knows how to solve advanced issues with ease, definitely recommended if you need a problem solved.

Thank you!
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
You are most welcome and thank you for those kind words and the points.
0
 

Author Comment

by:Richard Morris
Comment Utility
@julianH

I ran into a problem with the script and posted a new thread about the problem worth 500 points at:

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_28406737.html

Hope you can help.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now