Chris Jason Barredo Chris Jason Barredo - 16 days ago 7
Javascript Question

alternate running timer jquery

I want to make a timer that when idle is running talk is pause and vice versa and when I click idle, idle will resume its counting and vice versa



var count_idle = $('#ctr_idle').text();
var count_talk = $('#ctr_talk').text();

function clock_idle() {
count_idle++;
$('#ctr_idle').text(count_idle);
}

function clock_talk() {
count_talk++;
$('#ctr_talk').html(count_talk);
}

$('#status').change(function() {
var choice = $('#status').val();
console.log(choice);

if (choice == 'talk') {
clearInterval(timer_idle);
var timer_talk = setInterval(clock_talk, 1000);

} else {
clearInterval(timer_talk);
var timer_idle = setInterval(clock_idle, 1000);
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="col-md-12">
<h1>TIMER
<select id = "status">
<option value="idle">Idle</option>
<option value="talk">Talk_time</option>
</select>
</h1>
<h3>Idle: <span id="ctr_idle"></span></h3>
<h3>Talk_time: <span id="ctr_talk"></span></h3>
</div>




Answer

Try like this:

var timer_talk ; var timer_idle; added with in global variable . Clear Interval is not working. Because the variable are private not a global

var count_idle = $('#ctr_idle').text();
var count_talk = $('#ctr_talk').text();
var timer_talk ;//global
var timer_idle;//global
function clock_idle() {
  count_idle++;
  $('#ctr_idle').text(count_idle);
}

function clock_talk() {
  count_talk++;
  $('#ctr_talk').html(count_talk);
}

$('#status').change(function() {
  var choice = $('#status').val();
  console.log(choice);

  if (choice == 'talk') {
    clearInterval(timer_idle);
    timer_talk = setInterval(clock_talk, 1000);

  } else {
    clearInterval(timer_talk);
     timer_idle = setInterval(clock_idle, 1000);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="col-md-12">
  <h1>TIMER
    <select id = "status">
      <option value="idle">Idle</option>
      <option value="talk">Talk_time</option>
    </select>
  </h1>
  <h3>Idle: <span id="ctr_idle"></span></h3>
  <h3>Talk_time: <span id="ctr_talk"></span></h3>
</div>

Comments