user3386779 user3386779 - 5 months ago 28
jQuery Question

integrate four functions into single function

I have four counter in a single page I have called separate function for each function.I need to integrate all function into single function.



var tt1 = setInterval(function() {
startTimee()
}, 50);
var counter1 = 1;

function startTimee() {
if (counter1 == 10) {
clearInterval(tt1);
} else {
counter1++;
}
document.getElementById('counter1').innerHTML = counter1;

}
var tt = setInterval(function() {
startTime()
}, 5);
var counter = 1;

function startTime() {
if (counter == 600) {
clearInterval(tt);
} else {
counter++;
}
document.getElementById('counter2').innerHTML = counter;
}
var tt2 = setInterval(function() {
startTime2()
}, 50);
var counter2 = 1;

function startTime2() {
if (counter2 == 30) {
clearInterval(tt2);
} else {
counter2++;
}
document.getElementById('count3').innerHTML = counter2;
}
var tt3 = setInterval(function() {
startTime3()
}, 50);
var counter3 = 1;

function startTime3() {
if (counter3 == 6) {
clearInterval(tt3);
} else {
counter3++;
}
document.getElementById('counter4').innerHTML = counter3;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter1">10</div>
<div id="counter2">600</div>
<div id="counter3">30</div>
<div id="counter4">6</div>




Answer

You can do something like:

var time = 1, interval = setInterval(tick, 50);

function tick()
{
  if (time <= 10)
    document.getElementById('counter1').innerHTML = time;

  if (time <= 600)
    document.getElementById('counter2').innerHTML = time;

  if (time <= 30)
    document.getElementById('counter3').innerHTML = time;

  if (time <= 6)
    document.getElementById('counter4').innerHTML = time;     

  if (++time > 600) 
    clearInterval(interval); 
}
<p id="counter1"></p>
<p id="counter2"></p>
<p id="counter3"></p>
<p id="counter4"></p>

It is far not the most optimal code, but it is just an example for you to get the main principle.