将四个函数集成到单个函数中

时间:2016-07-01 04:37:26

标签: javascript jquery html

我在一个页面中有四个计数器我为每个函数调用了单独的函数。我需要将所有函数集成到单个函数中。

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>

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

&#13;
&#13;
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); 
}
&#13;
<p id="counter1"></p>
<p id="counter2"></p>
<p id="counter3"></p>
<p id="counter4"></p>
&#13;
&#13;
&#13;

它不是最优化的代码,但它只是一个例子,你可以得到主要原则。

答案 1 :(得分:2)

根据值的来源,您可以采取几种方法。

第一个选项是创建一个包含span&#39; id的对象和要计数的最大值。

&#13;
&#13;
var countCeiling = {
  counter1: {
    end: 10
  },
  counter2: {
    end: 600,
    start: 0
  },
  counter3: {
    end: 30,
    start: 0
  },
  counter4: {
    end: 6,
    start: 0
  }
};

var timerID = setInterval(function() {
  var stopTimer = true;

  for (var id in countCeiling) {
    var data = countCeiling[id];
    var span = document.getElementById(id);

    var val = data.current || data.start || 0;

    data.current = val + 1;

    if (val <= data.end) {
      span.innerHTML = val;
      stopTimer = false;
    }

  }

  if (stopTimer) {
    clearInterval(timerID);
  }

});
&#13;
<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>
&#13;
&#13;
&#13;