最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create a count up timer in a text input? - Stack Overflow

programmeradmin2浏览0评论

Below I have a javascript count down timer which works fine:

    <h1><span id='countdown'><?php echo $dbSessionDuration; ?></span></h1>

...

  $(document).ready(function() {
    var time = <?php echo json_encode($dbSessionDuration); ?>,
      parts = time.split(':'),
      hours = +parts[0],
      minutes = +parts[1],
      seconds = +parts[2],
      span = $('#countdown');


    function correctNum(num) {
      return (num<10)? ("0"+num):num;
    }

    var timer = setInterval(function(){
        seconds--;
        if(seconds == -1) {
            seconds = 59;
            minutes--;

            if(minutes == -1) {
                minutes = 59;
                hours--;

                if(hours==-1) {
                  alert("timer finished");
                  clearInterval(timer);
                  return;
                }
            }
        }
        span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
    }, 1000);

});

Now what I thought of doing is use the example above and manipulate it to now do the opposite and create a count up timer starting with 00:00:00 (hours, mins, secs).

But issue is that it is not working. Nothing is happening. I don't know if I need an hours in the function below because as its a countup, the hours could go up to as many hours as it wants. But my question is how can the count up timer be fixed so that it is fully working?

<p><input type='text' class='responseTime' name='responsetime' value='00:00:00' /></p>

...

$(document).ready(function() {
var response = "00:00:00",
      parts = time.split(':'),
      hours = +parts[0],
      minutes = +parts[1],
      seconds = +parts[2],
      input = $('.responseTime');


    function correctResponse(responsenum) {
      return (responsenum<10)? ("0"+responsenum):responsenum;
    }

    var responsetimer = setInterval(function(){
        seconds--;
        if(seconds == +59) {
            seconds = 00;
            minutes--;

            if(minutes == +59) {
                minutes = 00;
                hours--;

                  return;

            }
        }
        input.text(correctResponse(hours) + ":" + correctResponse(minutes) + ":" + correctResponse(seconds));
    }, 1000);


  });

UPDATE:

Also as a side note I realised that the countdown timer I believe is counting down every 2 second for every second. How can this be sorted for the count down timer and included in the count up timer?

The code below I have changed to include increment ++ and to include .val rather than .text but what is happening is that it starts with 00:00:00 and then it just drops down to 00:59:60 and then just stops:

var response = "00:00:00",
          parts = time.split(':'),
          hours = +parts[0],
          minutes = +parts[1],
          seconds = +parts[2],
          input = $('.responseTime');


        function correctResponse(responsenum) {
          return (responsenum<10)? ("0"+responsenum):responsenum;
        }

        var responsetimer = setInterval(function(){
            seconds++;
            if(seconds == +59) {
                seconds = 00;
                minutes++;

                if(minutes == +59) {
                    minutes = 00;
                    hours++;

                      return;

                }
            }
            input.val(correctResponse(hours) + ":" + correctResponse(minutes) + ":" + correctResponse(seconds));
        }, 1000);


      }); 

Below I have a javascript count down timer which works fine:

    <h1><span id='countdown'><?php echo $dbSessionDuration; ?></span></h1>

...

  $(document).ready(function() {
    var time = <?php echo json_encode($dbSessionDuration); ?>,
      parts = time.split(':'),
      hours = +parts[0],
      minutes = +parts[1],
      seconds = +parts[2],
      span = $('#countdown');


    function correctNum(num) {
      return (num<10)? ("0"+num):num;
    }

    var timer = setInterval(function(){
        seconds--;
        if(seconds == -1) {
            seconds = 59;
            minutes--;

            if(minutes == -1) {
                minutes = 59;
                hours--;

                if(hours==-1) {
                  alert("timer finished");
                  clearInterval(timer);
                  return;
                }
            }
        }
        span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
    }, 1000);

});

Now what I thought of doing is use the example above and manipulate it to now do the opposite and create a count up timer starting with 00:00:00 (hours, mins, secs).

But issue is that it is not working. Nothing is happening. I don't know if I need an hours in the function below because as its a countup, the hours could go up to as many hours as it wants. But my question is how can the count up timer be fixed so that it is fully working?

<p><input type='text' class='responseTime' name='responsetime' value='00:00:00' /></p>

...

$(document).ready(function() {
var response = "00:00:00",
      parts = time.split(':'),
      hours = +parts[0],
      minutes = +parts[1],
      seconds = +parts[2],
      input = $('.responseTime');


    function correctResponse(responsenum) {
      return (responsenum<10)? ("0"+responsenum):responsenum;
    }

    var responsetimer = setInterval(function(){
        seconds--;
        if(seconds == +59) {
            seconds = 00;
            minutes--;

            if(minutes == +59) {
                minutes = 00;
                hours--;

                  return;

            }
        }
        input.text(correctResponse(hours) + ":" + correctResponse(minutes) + ":" + correctResponse(seconds));
    }, 1000);


  });

UPDATE:

Also as a side note I realised that the countdown timer I believe is counting down every 2 second for every second. How can this be sorted for the count down timer and included in the count up timer?

The code below I have changed to include increment ++ and to include .val rather than .text but what is happening is that it starts with 00:00:00 and then it just drops down to 00:59:60 and then just stops:

var response = "00:00:00",
          parts = time.split(':'),
          hours = +parts[0],
          minutes = +parts[1],
          seconds = +parts[2],
          input = $('.responseTime');


        function correctResponse(responsenum) {
          return (responsenum<10)? ("0"+responsenum):responsenum;
        }

        var responsetimer = setInterval(function(){
            seconds++;
            if(seconds == +59) {
                seconds = 00;
                minutes++;

                if(minutes == +59) {
                    minutes = 00;
                    hours++;

                      return;

                }
            }
            input.val(correctResponse(hours) + ":" + correctResponse(minutes) + ":" + correctResponse(seconds));
        }, 1000);


      }); 
Share Improve this question edited Feb 7, 2013 at 22:33 user1914374 asked Feb 7, 2013 at 22:21 user1914374user1914374 1,2602 gold badges11 silver badges21 bronze badges 7
  • 1 Not sure if I'm missing something, but it looks like your decrementing seconds, yet checking for it to be a positive number. Maybe you should try incrementing ? – Rake36 Commented Feb 7, 2013 at 22:26
  • @Rake36 Please look at update – user1914374 Commented Feb 7, 2013 at 22:33
  • @user1914374: Please don't keep changing your question / updating it as you get new answers. – Oerd Commented Feb 7, 2013 at 22:36
  • @Oerd It is only to show what current code looks like so you know what is happening. Shall I just remove it? – user1914374 Commented Feb 7, 2013 at 22:38
  • No, it's ok, just don't change it so that this question bees another one ;) – Oerd Commented Feb 7, 2013 at 22:39
 |  Show 2 more ments

5 Answers 5

Reset to default 2

You could easily modify the current countdown timer like here: http://jsfiddle/Sergiu/CDpeJ/3

var timer = setInterval(function(){
    seconds++;
    if(seconds == 60) {
        seconds = 00;
        minutes++;

        if(minutes == 60) {
            minutes = 00;
            hours++;
        }
    }
    var newTime = hours + ":" + minutes + ":" + seconds;
    if(!newTime.match(/^(20|21|22|23|[01]\d|\d)(([:.][0-5]\d){1,2})$/)) newTime = "finished";
    $('#timeInput').val(newTime);
}, 1000);

In jQuery, use the val('value') function to change/set the value of an input field.

Change input.text(...) to input.val(...)

Also:

  1. After incrementing seconds use seconds = seconds % 60; to bring them back to 0.
  2. Also, consider using data-attributes for passing values to javascript.

This is how I would have implemented such a timer:

function startTimer() {
    var time = 0
    setInterval(function(){
        time++
        var sec = time % 60
        var min = (time-sec)/60 % 60
        var hour = (time-sec-min*60)/3600
        var str= hour+':'+("0"+min).slice(-2)+':'+("0"+sec).slice(-2)
        $('.responseTime').val(str)
    },1000);
}

With an input with class responseTime to display the timer. (Why not use id btw?)

Start whenever appropriate calling startTimer() (in your example using document.onload=startTimer)

If you want to start from another time than 0, set time to the appropriate number of seconds. For a countdown, replace time++ with time-- (probably adding some logistics for time==0)

Count up try this

var millis = <?php echo $dbSessionDurationTime; ?> ( diff in seconds )

function displaytimer(){
    var hours = Math.floor(millis / 36e5),
        mins = Math.floor((millis % 36e5) / 6e4),
        secs = Math.floor((millis % 6e4) / 1000);
        //Here, the DOM that the timer will appear using jQuery
        $('.count').html(hours+':'+mins+':'+secs);  
}

setInterval(function(){
    millis += 1000;
    displaytimer();
}, 1000);

I added Mariusnn solution and Oerd suggestion to JSFiddle with changing val to text in Jquery.

HTML file

<body> <h1 style="color:blue">Time</h1> <h2><span class="responseTime" style="color:indianred"></span> </h2> </body>

JS code

` var startTimer;

startTimer = function() {
var time;
time = 0;
setInterval((function() {
    var hour, min, sec, str;
    time++;
    sec = time % 60;
    min = (time - sec) / 60 % 60;
    hour = (time - sec - (min * 60)) / 3600;
    count = hour + ':' + ('0' + min).slice(-2) + ':' + ('0' + sec).slice(-2);
    $('.responseTime').text(count);
    }), 1000);
   };

$( document ).ready(function() {
    startTimer();
});

`

JS fiddle solution is here.

https://jsfiddle/hzLf3e38/4/

发布评论

评论列表(0)

  1. 暂无评论