user3476168 user3476168 - 7 months ago 25
Javascript Question

Increase variables

I am trying to use the JavaScript below to display number increment within set time frame. The problem I have is that I am trying to use them in two different cases with different sent values but they conflict with each other by displaying the same value. How can I use them in different cases without conflicting eachother. See code below:



<script>
var START_DATE = new Date("January 10, 2012 22:30:00"); // put in the starting date here
var INTERVAL = 8; // refresh interval in seconds
var INCREMENT = 6; // increase per tick
var START_VALUE = 25; // initial value when it's the start date
var count = 0;
$(document).ready(function() {
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
$('#div1').html(count.toFixed(0));
window.setInterval( function(){
count += INCREMENT;
$('#div1').html(count.toFixed(0));
}, msInterval);
});
</script>
<div id="div1"></div>

<script>
var START_DATE = new Date("January 10, 2012 22:30:00"); // put in the starting date here
var INTERVAL = 14; // refresh interval in seconds
var INCREMENT = 5; // increase per tick
var START_VALUE = 15000; // initial value when it's the start date
var count = 0;
$(document).ready(function() {
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
$('#div2').html(count.toFixed(0));
window.setInterval( function(){
count += INCREMENT;
$('#div2').html(count.toFixed(0));
}, msInterval);
});
</script>
<div id="div2"></div>





They are meant to display different output based on the set values but they are displaying same values

I will appreciate full explanation with example.

Answer

Use one function countersUpdate with local variables msInterval and count and parameters elm, INTERVAL, INCREMENT, START_VALUE

var now = new Date();
var START_DATE = new Date("January 10, 2012 22:30:00");

function countersUpdate(elm, INTERVAL, INCREMENT, START_VALUE) {
  var msInterval = INTERVAL * 1000;
  var count = parseInt((now - START_DATE) / msInterval) * INCREMENT + START_VALUE;
  elm.html(count.toFixed(0));
  window.setInterval(function() {
    count += INCREMENT;
    elm.html(count.toFixed(0));
  }, msInterval);
}

countersUpdate($('#div1'), 8, 6, 25);
countersUpdate($('#div2'), 14, 5, 1500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="div1"></div>
<div id="div2"></div>