Juan Camacho Juan Camacho - 1 year ago 61
jQuery Question

Why I can't increment the chronometer value?

I would like a time counter and I found the next code. The problem is when I change

time = new Date(time - 1000);
time = new Date(time + 1000);

This is my code:

<!DOCTYPE html>
<meta charset="utf-8">
<title>My page</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
margin: 0 10px;
color: gray;
font-size: 50px;
margin: 20px;
font-family: monospace;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
var startValue = 1000; //Number of milliseconds
var time = new Date(startValue);
var interv;
$(".start").on("click", function(){
interv = setInterval(function(){
//time = new Date(time - 1000);
time = new Date(time + 1000);
}, 1000);
$(".stop").on("click", function(){
time = new Date(startValue);
$(".pause").on("click", function(){
$(".reset").on("click", function(){
time = new Date(startValue);

function displayTime(){
$(".time").text(fillZeroes(time.getMinutes()) + ":" + fillZeroes(time.getSeconds()));

function fillZeroes(t){
t += "";
return t.length==1? "0" + t : t;
<a href="#" class="start">start</a>
<a href="#" class="stop">stop</a>
<a href="#" class="pause">pause</a>
<a href="#" class="reset">reset</a>
<div class="time"></div>

How I can increment the time?
Thank you!

Answer Source

Use date.getTime() to get a timestamp from a Date object. In your case:

time = new Date(time.getTime() + 1000);

Demo: https://plnkr.co/edit/G8yo5l4wHe2yv9S3fjLI?p=preview

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download