I would like a time counter and I found the next code. The problem is when I change time = new Date(time - 1000);
to time = new Date(time + 1000);
This is my code:
<!DOCTYPE html>
<html>
<head>
<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">
<style>
a{
margin: 0 10px;
color: gray;
}
.time{
font-size: 50px;
margin: 20px;
font-family: monospace;
}
</style>
<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>
<script>
var startValue = 1000; //Number of milliseconds
var time = new Date(startValue);
var interv;
$(function(){
displayTime();
$(".start").on("click", function(){
interv = setInterval(function(){
//time = new Date(time - 1000);
time = new Date(time + 1000);
displayTime();
}, 1000);
});
$(".stop").on("click", function(){
clearInterval(interv);
time = new Date(startValue);
displayTime();
});
$(".pause").on("click", function(){
clearInterval(interv);
});
$(".reset").on("click", function(){
time = new Date(startValue);
displayTime();
});
});
function displayTime(){
$(".time").text(fillZeroes(time.getMinutes()) + ":" + fillZeroes(time.getSeconds()));
}
function fillZeroes(t){
t += "";
return t.length==1? "0" + t : t;
}
</script>
</head>
<body>
<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>
</body>
</html>
How I can increment the time? Thank you!
Use date.getTime()
to get a timestamp from a Date object. In your case:
time = new Date(time.getTime() + 1000);
try this solution https://jsfiddle.net/giuseppe_straziota/eag01ojj/
$(".start").on("click", function(){
interv = setInterval(function(){
time.setSeconds(time.getSeconds() + 1);
displayTime();
}, 1000);
});
The problem is that you try to instanciate a Date object with another Date object as argument.
var time = new Date(startValue);
...
time = new Date(time + 1000);
Try to use console.log() next time for debug.
You also have a few other problems, like why do you start your counter at 1 instead of zero ?
Here is a quick working example that should fix everything: https://jsfiddle.net/r6k06w40/3/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.