JSFiddle - React, Tailwind, and code Playground

by Elias Barbosa

HTML

<span id="jqcd_count">00:30</span><br><br>
<input type="button" id="jqcd_start" value="Start" onClick="jqcd('start')" />
<input type="button" id="jqcd_stop" value="Stop" onClick="jqcd('stop')" /><br><br>
<input type="text" id="jqcd_time" value="00:10" />

CSS

input#jqcd_start,
input#jqcd_stop,
span#jqcd_count {
  font-size: 20pt;
  font-weight: bold;
}
input#jqcd_start,
input#jqcd_stop {
  width: 150px;
}
span#jqcd_count {
  font-family: "Lucida Console", Monaco, "Courier New", Courier, monospace !IMPORTANT;
}

JavaScript

var jqcd_start_id = 'input#jqcd_start';
var jqcd_stop_id = 'input#jqcd_stop';
var jqcd_time_id = 'input#jqcd_time';
var jqcd_count_id = 'span#jqcd_count';
var jqcd_end_message = 'Time is up!';

var jqcd_countdown = '';
var jqcd_status = 'stopped';
var jqcd_current = '';

function jqcd(action){
  
  if (action == 'start') {
    if (jqcd_status == 'stopped') {
	  jqcd_updtv(jqcd_start_id, 'Pause');
	  jqcd_status = 'running';
	  jqcd_current = jqcd_countdown;
      jqcd_updtt(jqcd_count_id, jqcd_countdown);
    }
    else if (jqcd_status == 'running') {
	  jqcd_updtv(jqcd_start_id, 'Resume');
      jqcd_status = 'paused';
    }
    else if (jqcd_status == 'paused') {
	  jqcd_updtv(jqcd_start_id, 'Pause');
      jqcd_status = 'running';
    }
  }
  else if (action == 'stop') {
	jqcd_updtv(jqcd_start_id, 'Start');
    jqcd_status = 'stopped';
	jqcd_updtt(jqcd_count_id, jqcd_countdown);
  }
  
  var a =  jqcd_current.split(":");
  var m = a[0];
  var s = (a[1] - 1);
  
  if (s < 0) {
    if (parseInt(m) == 0) {
	  jqcd_updtv(jqcd_start_id, 'Start');
      jqcd_status = 'stopped';
      jqcd_updtt(jqcd_count_id, jqcd_end_message);
    }
    else {
      m = m - 1;
      s = 59;
    }
  }
  
  if(s >= 0){
    setTimeout(function(){
      if (jqcd_status == 'running') {
	    m = (parseInt(m) < 10)? "0" + parseInt(m): m;
	    s = (parseInt(s) < 10)? "0" + parseInt(s): s;
        jqcd_updtt(jqcd_count_id, m + ":" + s);
        jqcd_current = m + ":" + s;
        jqcd('');
      }
    }, 1000);
  }
}

function jqcd_updtv(selector, value) {
  if (selector != '') {
    $(selector).val(value);
  }
}
function jqcd_updtt(selector, value) {
  if (selector != '') {
    $(selector).text(value);
  }
}

$(document).ready(function() {
	jqcd_countdown = $(jqcd_time_id).val();
	jqcd_updtt(jqcd_count_id, jqcd_countdown);
	
	$(jqcd_time_id).keyup(function() {
      jqcd_countdown = $(jqcd_time_id).val();
      jqcd_updtt(jqcd_count_id, jqcd_countdown);
    });
});