how to set the same id for multiple element in html - javascript

I want to use countdown timer for 10 element that creating at run time. each element has expire time so I want to show user how much time of of the expiration is remained.so I use a jquery file to do this .so I must use an id for a tag to show the remained time .when I use it for one element it works fine but when I use it for multiple element it just works for first element.how can I solve this problem to show the remained time for all elements
Jquery file
//var count = 1000;
//var counter = setInterval(timer, 1000);
//function timer() {
// count -= 1;
// if (count==1000) {
// clearInterval(counter);
// }
// document.getElementById("num").innerHTML = count;
//}
function CountDown() {
this.start_time = "02:00:00:23";
this.target_id = "#timer";
this.name = "timer";
}
CountDown.prototype.init=function(){
this.reset();
setInterval(this.name+'.tick()',1000);
}
CountDown.prototype.reset=function(){
time = this.start_time.split(":");
this.days = parseInt(time[0]);
this.hours = parseInt(time[1]);
this.minutes=parseInt(time[2]);
this.seconds = parseInt(time[3]);
this.update_target();
}
CountDown.prototype.tick=function(){
if (this.seconds > 0 || this.minutes > 0 || this.hours > 0 ||this.days>0) {
if (this.hours == 0 && this.minutes == 0 && this.seconds == 0) {
this.days = this.days - 1;
this.hours = 23;
this.minutes = 59;
this.seconds = 59;
}
if (this.minutes == 0 && this.seconds==0) {
this.hours = this.hours - 1;
this.minutes = 59;
this.seconds = 59;
}
else if (this.seconds == 0) {
this.minutes = this.minutes - 1;
this.seconds = 59;
}
else {
this.seconds = this.seconds - 1;
}
}
this.update_target();
}
CountDown.prototype.update_target = function () {
seconds = this.seconds;
minutes = this.minutes;
hours = this.hours;
days = this.days;
if (seconds<10)
seconds = "0"+seconds;
if (minutes < 10)
minutes = "0"+ minutes;
if (hours < 10)
hours = "0" + hours;
if (days < 10)
days = "0" + days;
$(this.target_id).val(days+":"+hours+":"+minutes + ":" + seconds)
// $(this.target_id).val(this.minutes+":"+seconds)
}
Html
<script src="~/Scripts/jquery-1.4.4.min.js"></script>
<script src="~/Scripts/countdown.js"></script>
<input type="text" id="timer" value=" " />
<script>
timer = new CountDown();
timer.init();
</script>

Id is unique in html use class instead .. more element can have the same class
$('.yourClass')
instead of
$('#yourId')
.
<script src="~/Scripts/jquery-1.4.4.min.js"></script>
<script src="~/Scripts/countdown.js"></script>
<input type="text" class="timer" value=" " />
<script>
timer = new CountDown();
timer.init();
</script>
function CountDown() {
this.start_time = "02:00:00:23";
this.target_id = ".timer";
this.name = "timer";
}

EDIT :
I've created a JSFiddle for it, can you precise your request ?
See it here
I changed this :
timer = new CountDown("02:00:00:23");
timer.init();
And this function :
function CountDown(start_time) {
this.start_time = start_time;
this.target_id = ".timer";
this.name = "timer";
}

Id's are unique and should only be used once in an html page. Also, and element should only have a single ID. Classes are not unique so multiple elements can have the same class, also, a single element can have multiple classes. Example:
<div class="exampleClass anotherClass"></div>
<div class="exampleClass></div>
<div class="exampleClass></div>
Instead of id="timer" use class="timer" then in your javascript file use $(".timer") to target those classes. So in your case instead of this.target_id = "#timer" use this.target_id =".timer";
Here's a good reference for classes and ids.

Related

How to convert a stopwatch to a count down timer in JS

Is it possible to modify that code of a stopwatch bellow in a way that it works as a count down timer that starts from 00:13:00 and stops at 00:00:00. The start and reset button should function as before.
//Define vars to hold time values
let seconds = 0;
let minutes = 0;
let hours = 0;
//Define vars to hold "display" value
let displaySeconds = 0;
let displayMinutes = 0;
let displayHours = 0;
//Define var to hold setInterval() function
let interval = null;
//Define var to hold stopwatch status
let status = "stopped";
//Stopwatch function (logic to determine when to increment next value, etc.)
function stopWatch(){
seconds++;
//Logic to determine when to increment next value
if(seconds / 60 === 1){
seconds = 0;
minutes++;
if(minutes / 60 === 1){
minutes = 0;
hours++;
}
}
//If seconds/minutes/hours are only one digit, add a leading 0 to the value
if(seconds < 10){
displaySeconds = "0" + seconds.toString();
}
else{
displaySeconds = seconds;
}
if(minutes < 10){
displayMinutes = "0" + minutes.toString();
}
else{
displayMinutes = minutes;
}
if(hours < 10){
displayHours = "0" + hours.toString();
}
else{
displayHours = hours;
}
//Display updated time values to user
document.getElementById("display").innerHTML = displayHours + ":" + displayMinutes + ":" + displaySeconds;
}
function startStop(){
if(status === "stopped"){
//Start the stopwatch (by calling the setInterval() function)
interval = window.setInterval(stopWatch, 1000);
document.getElementById("startStop").innerHTML = "Stop";
status = "started";
}
else{
window.clearInterval(interval);
document.getElementById("startStop").innerHTML = "Start";
status = "stopped";
}
}
//Function to reset the stopwatch
function reset(){
window.clearInterval(interval);
seconds = 0;
minutes = 0;
hours = 0;
document.getElementById("display").innerHTML = "00:00:00";
document.getElementById("startStop").innerHTML = "Start";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Stopwatch</title>
<link href="https://fonts.googleapis.com/css2?family=Concert+One&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
<script type="text/javascript" src="scripts.js"></script>
</head>
<body>
<div class="container">
<div id="display">
00:13:00
</div>
<div class="buttons">
<button id="startStop" onclick="startStop()">Start</button> <button id="reset" onclick="reset()">Reset</button>
</div>
</div>
</body>
</html>
I have tried setting the initial time 00:13:00 and using a -- operator instead of ++ operators. But it just shows negative time.
(Not including the CSS as it will stay the same)
The if statements below //Logic to determine when to increment next value need to be changed to seconds < 0 and minutes < 0
//Define vars to hold time values
let seconds = 0;
let minutes = 1;
let hours = 0;
//Define vars to hold "display" value
let displaySeconds = 0;
let displayMinutes = 0;
let displayHours = 0;
//Define var to hold setInterval() function
let interval = null;
//Define var to hold stopwatch status
let status = "stopped";
//Stopwatch function (logic to determine when to increment next value, etc.)
function stopWatch() {
seconds--;
//Logic to determine when to increment next value
if (seconds < 0) {
if (minutes === 0 && hours === 0) {
clearInterval(interval);
alert("done!");
return;
} else {
seconds = 59;
minutes--;
if (minutes < 0) {
minutes = 59;
hours--;
}
}
}
//If seconds/minutes/hours are only one digit, add a leading 0 to the value
if (seconds < 10) {
displaySeconds = "0" + seconds.toString();
} else {
displaySeconds = seconds;
}
if (minutes < 10) {
displayMinutes = "0" + minutes.toString();
} else {
displayMinutes = minutes;
}
if (hours < 10) {
displayHours = "0" + hours.toString();
} else {
displayHours = hours;
}
//Display updated time values to user
document.getElementById("display").innerHTML = displayHours + ":" + displayMinutes + ":" + displaySeconds;
}
function startStop() {
if (status === "stopped") {
//Start the stopwatch (by calling the setInterval() function)
interval = window.setInterval(stopWatch, 1000);
document.getElementById("startStop").innerHTML = "Stop";
status = "started";
} else {
window.clearInterval(interval);
document.getElementById("startStop").innerHTML = "Start";
status = "stopped";
}
}
//Function to reset the stopwatch
function reset() {
window.clearInterval(interval);
seconds = 0;
minutes = 13;
hours = 0;
document.getElementById("display").innerHTML = "00:00:00";
document.getElementById("startStop").innerHTML = "Start";
}
<div class="container">
<div id="display">
00:01:00
</div>
<div class="buttons">
<button id="startStop" onclick="startStop()">Start</button> <button id="reset" onclick="reset()">Reset</button>
</div>
</div>

What is wrong with countdown timer program?

I'm trying to make a countdown timer to go from 15 minutes 0 seconds to 0 minutes 0 seconds but it appears that it doesn't want to display in JsFiddle. Another program is that my date variable isn't actually set to 15 minutes and 0 seconds. How can I fix this?
var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
var handler = function() {
sec--;
if (sec == 60) {
sec = 0;
min--;
else if (sec < 0) {
date.setSeconds(0);
} else if (min < 0) {
date.setMinutes(0);
}
}
document.getElementById("time").innerHTML = (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec);
};
handler();
setInterval(handler, 1000);
<b>Offer Ends In:</b>
<h1 id="time" style="text-align: center"></h1>
Well, for one thing, you don't have a closing brace before the else, so it won't even run as is.
In addition, I'm not sure why you need to fiddle around with date objects for a countdown timer, since the current date/time is irrelevant.
You should start with something like:
function pad2(s) {
return ("00" + s).slice(-2);
}
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
document.getElementById("time").innerHTML = pad2(min) + ":" + pad2(sec);
};
var sec = 1;
var min = 15;
handler();
setInterval(handler, 1000);
You'll notice I've refactored out the padding code since it's "questionable" whether you should ever violate the DRY principle. You certainly shouldn't violate it twice on a single line :-)
In terms of testing, you can create a simple static page which runs the timer as follows.
I've also reduced starting time to a little over ten minutes and accelerated time ten-fold so you don't have to wait around for a full quarter hour to test the whole thing (it should take a smidgen more than a minute to complete).
<html>
<body>
<b>Offer Ends In:</b>
<h1 id="time" style="text-align: left"></h1>
<script type="text/javascript">
function pad2(s) {
return ("00" + s).slice(-2);
}
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = sec = 0;
}
}
document.getElementById("time").innerHTML = pad2(min) + ":" + pad2(sec);
};
var sec = 6;
var min = 10;
handler();
setInterval(handler, 100); // 10x normal speed, use 1000 for reality
</script>
</body>
</html>
For starters, you do not have a closing brace before the else if and you need to remove the brace before your document.getElementById
1) Closed your curly-bracket for your if condition.
2) Your code failed to load properly because your JavaScript loads before the page recognizes the time DIV element. Since you didn't use an event listener for the page loading first, I added that... and it seems to be working.
3) Important note... The timer logic needs a lot of work... You're better off using a time DIFF statement otherwise you've got about 200-300 lines more to write just on calculating seconds, minutes, hours, days etc.
Looking at the page as it stands has this... 15:0-289
** Update ** adding the padding technique rectified the above note...
Here's a solution for that.
Check time difference in Javascript
<html>
<head>
<script type="text/javascript">
var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
document.addEventListener("DOMContentLoaded", function(event) {
var myTimer = setInterval(handler, 1000);
});
function pad2(s) {
return ("00" + s).slice(-2);
}
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
document.getElementById("time").innerHTML = pad2(min) + ":" + pad2(sec);
};
</script>
</head>
<body>
<b>Offer Ends In:</b>
<h1 id="time" style="text-align: center"></h1>
</body>
</html>
I just made this StopWatch. You can use it without a button and it will work like you want.
//<![CDATA[
/* external.js */
var doc, bod, htm, C, E, T, MillisecondConverter, StopWatch; // for use on other loads
addEventListener('load', function(){
var doc = document, bod = doc.body, htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
T = function(tag){
return doc.getElementsByTagName(tag);
}
MillisecondConverter = function(milliseconds, displayMilliseconds){
var ms = milliseconds, rh = ms/3600000, hp = Math.pow(10, rh.toString().length-2);
this.hours = Math.floor(rh);
var rm = (rh*hp-this.hours*hp)/hp*60, mp = Math.pow(10, rm.toString().length-2);
this.minutes = Math.floor(rm);
var rs = (rm*mp-this.minutes*mp)/mp*60, sp = Math.pow(10, rs.toString().length-2);
if(displayMilliseconds){
this.seconds = Math.floor(rs);
this.milliseconds = Math.round((rs*sp-this.seconds*sp)/sp*1000);
}
else{
this.seconds = Math.round(rs);
}
this.convert = function(){
return this.hours.toString().replace(/^([0-9])$/, '0$1')+':'+this.minutes.toString().replace(/^([0-9])$/, '0$1')+':'+this.seconds.toString().replace(/^([0-9])$/, '0$1');
}
}
StopWatch = function(displayNode, millisecondInterval){
this.hours = this.minutes = this.seconds = this.milliseconds = 0;
this.millisecondInterval = millisecondInterval || 1000;
this.displayNode = displayNode; this.began = false; this.paused = false;
var t = this, ms, iv, fi;
this.begin = function(doneFunc, context){
var c = context || this;
ms = this.hours*3600000+this.minutes*60000+this.seconds*1000+this.milliseconds;
var mc = new MillisecondConverter(ms), dn = this.displayNode, cv = mc.convert();
if(dn.innerHTML || dn.innerHTML === ''){
dn.innerHTML = cv;
}
else{
dn.value = cv;
}
this.began = true;
fi = function(mi){
var nd = new Date, bt = nd.getTime(), ii = t.millisecondInterval;
ms = mi;
iv = setInterval(function(){
var nd = new Date, ct = nd.getTime(), tl = ct-bt;
var mc = new MillisecondConverter(mi-tl), dn = t.displayNode;
if(tl >= mi){
clearInterval(iv); doneFunc.call(c); cv = '00:00:00';
if(dn.innerHTML || dn.innerHTML === ''){
dn.innerHTML = cv;
}
else{
dn.value = cv;
}
t.began = false;
return;
}
cv = mc.convert(); ms -= ii;
if(dn.innerHTML || dn.innerHTML === ''){
dn.innerHTML = cv;
}
else{
dn.value = cv;
}
}, ii);
}
fi(ms);
}
this.pause = function(){
clearInterval(iv); iv = undefined; this.paused = true;
return this;
}
this.resume = function(){
fi(ms); this.paused = false;
return this;
}
}
var cd = new StopWatch(E('remain')), out = E('out');
cd.seconds = 30;
E('btn').addEventListener('click', function(){
if(!cd.began){
out.innerHTML = '';
cd.begin(function(){
out.innerHTML = 'Countdown Complete';
});
}
else{
cd.paused ? cd.resume() : cd.pause();
}
});
});
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>StopWatch</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div id='remain'>00:00:30</div>
<input id='btn' type='button' value='StopWatch' />
<div id='out'></div>
</div>
</body>
</html>

How can I modify my function to be able to cancel the interval from anywhere in the controller

I am trying to create a countdown and I want to be able to cancel the interval not only when reach 0 but with clicking of a button as well.How can I modify my function to be able to cancel the interval from anywhere in the controller.
function countDown(total) {
total = total * 60;
var interval = $interval(function () {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1)
{
minutes = '0:';
}
else
{
minutes = minutes + ':';
}
if (seconds < 10)
{
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if(minutes === '0:' && seconds === '00')
{
$interval.cancel(interval);
}
}, 1000);
}
As suggested by other users, you should make interval global in the controller. Then on the other functions you want to cancel the interval you can call it safely.
Take a look at the below sample:
angular.module('app', [])
.controller('ctrl', function($interval) {
var self = this;
var interval;
self.wizard = {
startInterval: startInterval,
cancelInterval: cancelInterval
};
startInterval();
return self.wizard;
function startInterval() {
countDown(24);
}
function cancelInterval() {
$interval.cancel(interval);
}
function countDown(total) {
cancelInterval();
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.wizard.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-app="app" ng-controller="ctrl as ctrl">
<span ng-bind="ctrl.remainingTime"> </span>
<br/>
Cancel Interval
<br/>
Start Interval
</span>
I created an example using self instead of $scope like you are in your snippet above. As others mentioned moving the interval var to the global scope fixes this. I also added a stop and start function to test the issue you mentioned in the example above.
UPDATED - I added some code to the stop interval to reset the interval to undefined. I found an example of this usage on Angular's site so it might be worth a try to see if it fixes your other issue.
var app = angular.module('app', []);
app.controller('BaseController', function($interval) {
var self = this;
var interval;
function countDown(total) {
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
self.stopInterval = function(){
if (angular.isDefined(interval)) {
$interval.cancel(interval);
interval = undefined;
}
}
self.startInterval = function(){
countDown(10);
}
});
Then in the html I added a button to start and stop the interval like so:
<body ng-app="app">
<div ng-controller="BaseController as baseCtrl">
{{ baseCtrl.remainingTime }}
<div>
<button ng-click="baseCtrl.startInterval()">Start Countdown</button>
<button ng-click="baseCtrl.stopInterval()">Stop Countdown</button>
</div>
</div>
</body>
You can view the codepen example here

Getting different values from a span

I want to create a website with multiple countdowns activated by a click, some of them have different time, others the same. When one finish I need to return it to his original countdown value, so you will be able to click it again.
I have the times (in seconds) inside a span .time, and that's how I get the time for the countdowns, however I don't know how to save the original time, so when one is clicked I get as "original time" always the first span .time.
Here is my code: http://jsfiddle.net/arglab/m19aojmu/16/
Javascript
function timer(selector) {
var description = ["seconds","hour"]
var self = $(selector);
var sec = parseInt(self.find('span.timeout').text());
console.log(sec)
order++;
var actualTime = $('span.timeout').html();
console.log("Original time " + actualTime)
self.addClass('selec').css('order',order+'');
var interval = setInterval(function() {
sec--;
console.log(sec)
if (sec >= 0) {
var hours = Math.floor(sec / 3600);
var min = Math.floor((sec - (hours*3600)) / 60);
var seconds = Math.floor(sec % 60);
var value = seconds;
if(min > 0) {
if(min == 1) {
value = " minute " + value;
} else {
value = " minutes " + value;
}
value = min + value;
}
if(hours > 0) {
if(hours == 1) {
value = " hour " + value;
} else {
value = " hours " + value;
}
value = hours + value;
}
self.find('span.timeout').text(value);
self.find('span.timeout').text(value);
} else if($(this).find('span').text() <= 0) {
console.log(sec)
var text = self.find('span.timeout').text(actualTime);
console.log(actualTime)
clearInterval(interval);
}
$('.element').each(function(){
if($(this).find('span').text() == 0){
$(this).removeClass('selec');
$(this).css('order','0');
}
});
}, 1000);
}
var order = 1;
$("body").on('click', '.element', function() {
timer(this);
});
HTML
<div id="container">
<div class="element" id="el1"><b>element 1</b> <span class="timeout">1000</span> seconds (1000)</div>
<div class="element" id="el2"><b>element 2</b> <span class="timeout">5</span> seconds (5)</div>
<div class="element" id="el3"><b>element 3</b> <span class="timeout">10</span> seconds (10)</div>
<div class="element" id="el4"><b>element 4</b> <span class="timeout">15</span> seconds (15)</div>
<div class="element" id="el5"><b>element 5</b> <span class="timeout">10</span> seconds (10)</div>
</div>
As you can see, if you click a 10 seconds countdown, when it finish his time isn't 10 seconds (as it should be) but, in this case, 1000 (first span .time)
What can I do? Thanks
You need to use self in your timer function.
Find the comments in the below code,
function timer(selector) {
var description = ["seconds", "hour"]
var self = $(selector);
var sec = parseInt(self.find('span.timeout').text());
console.log(sec)
order++;
var actualTime = self.find('span.timeout').html(); // use self.find here
console.log("Original time " + actualTime)
self.addClass('selec').css('order', order + '');
var interval = setInterval(function () {
sec--;
console.log(sec)
if (sec >= 0) {
var hours = Math.floor(sec / 3600);
var min = Math.floor((sec - (hours * 3600)) / 60);
var seconds = Math.floor(sec % 60);
var value = seconds;
if (min > 0) {
if (min == 1) {
value = " minute " + value;
} else {
value = " minutes " + value;
}
value = min + value;
}
if (hours > 0) {
if (hours == 1) {
value = " hour " + value;
} else {
value = " hours " + value;
}
value = hours + value;
}
self.find('span.timeout').text(value);
// remove the below redundant line
//self.find('span.timeout').text(value);
} else if (self.find('span').text() <= 0) { //use self not this
console.log(sec);
var text = self.find('span.timeout').text(actualTime);
console.log(actualTime)
clearInterval(interval);
}
$('.element').each(function () {
if ($(this).find('span').text() == 0) {
$(this).removeClass('selec');
$(this).css('order', '0');
}
});
}, 1000);
}
Live Demo
When registereing your onclick handler, you should pass another object to the timer function:
$("body").on('click', '.element', function(eve) {
timer(eve.target);
});

Timer to be displayed on a webpage

I want to add a count up timer to my webpage, as in, a label that contains 0:00:00 should start displaying 0:00:01 and so on until the stop button is clicked.
Is there a simple javascript/jquery solution to this?
<html>
<head>
<title>Home</title>
<script src="jquery-1.11.1.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
//psst. psst.
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td><input type="text" id="project" placeholder="project"></td>
<td><p id="timer">0:00:00<p></td>
</tr>
</table>
</form>
</body>
</html>
I tried something in Vanilla JS HERE
var seconds=0, minutes=0, hours=0;
var counter;
var stop,start;
var counting = false;
window.onload = function () {
counter = document.getElementById('counter');
stop = document.getElementById('stop');
stop.onclick = function () {
counting = false;
}
start = document.getElementById('start');
start.onclick = function() {
counting = true;
timer();
}
counting = true;
timer();
}
function timer() {
if (seconds >= 60) {
minutes++;
seconds = 0;
}
if (minutes >= 60) {
hours++;
minutes = 0;
}
counter.innerHTML = hours + ":" + minutes + ":" + seconds;
if (counting) {
seconds++;
setTimeout(timer, 1000);
}
}
If you need more info leave a comment..
time.js
function time(id)
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
// "setTimeout" call function "time" every 1 second (1000 milliseconds)
setTimeout('time("'+id+'");','1000');
return true;
}
HTML
<html>
<head>
<title>Time in Javascript</title>
<script type="text/javascript" src="time.js"></script>
</head>
<body>
<span id="time"></span>
<script type="text/javascript">window.onload = time('time');</script>
</body>
</html>
Try this way
Use https://github.com/jchavannes/jquery-timer
Include this files in head
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript">
<script src="http://jchavannes.com/include/scripts/3p/jquery.timer.js" type="text/javascript">
Script
var Example1 = new (function() {
var $stopwatch, // Stopwatch element on the page
incrementTime = 70, // Timer speed in milliseconds
currentTime = 0, // Current time in hundredths of a second
updateTimer = function() {
$stopwatch.html(formatTime(currentTime));
currentTime += incrementTime / 10;
},
init = function() {
$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
$(init);
});
function formatTime(time) {
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
}
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
Example1();
DEMO
By using setInterval and Date
You can use button to stop and start timer.
var d = new Date();
d.setHours(0,0,0,0);
setInterval((function(){
return function(){
d.setSeconds(d.getSeconds()+1);
var t = d.toLocaleTimeString("en-US", {hour12: false});
document.getElementById("demo").innerHTML = t;
}
})(), 1000);
Fiddle Demo
Please try this fiddle for your solution.
JS.
var hour = 0;
var min = 0;
var second = 0;
var i=setInterval(function(){
second++;
if(second > 59){
second = 0;
min++;
if(min>59){
hour++;
min = 0;
}
}
var timer_time = (hour > 9 ? hour : '0'+hour)+':'+(min > 9 ? min : '0'+min)+':'+(second > 9 ? second : '0'+second);
$('#timer').html(timer_time);
}, 1000);
$('#stop_timer').click(function(){
clearInterval(i);
});
HTML
<p id='timer'>00:00:00</p>
<button id='stop_timer'>Stop Timer</button>
Thanks
Use timing events like documented at http://www.w3schools.com/js/js_timing.asp.

Categories

Resources