plain count up timer in javascript
Check this:
var minutesLabel = document.getElementById("minutes");var secondsLabel = document.getElementById("seconds");var totalSeconds = 0;setInterval(setTime, 1000);
function setTime() { ++totalSeconds; secondsLabel.innerHTML = pad(totalSeconds % 60); minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));}
function pad(val) { var valString = val + ""; if (valString.length < 2) { return "0" + valString; } else { return valString; }}
<label id="minutes">00</label>:<label id="seconds">00</label>
create count up timer with typescript
Because the variable hour second minute are local to the function and will be zero on each call. So try this
//class variables
seconds = 0;
minutes = 0;
hours = 0;
recording(){
////// please type recording meeting functionality here
if (this.timer) {
this.seconds += 1;
if (this.seconds >= 60) {
this.seconds = 0;
this.minutes += 1
if (this.minutes >= 60) {
this.minutes = 0;
this.hours += 1
}
}
console.log(this.hours, this.minutes, this.seconds);
/// update recording time
this.recordingTimer = (this.hours ? (this.hours > 9 ? this.hours : "0" + this.hours) : "00") + ":" + (this.minutes ? (this.minutes > 9 ? this.minutes : "0" + this.minutes) : "00") + ":" + (this.seconds > 9 ? this.seconds : "0" + this.seconds);
console.log(this.recordingTimer)
}
Also dont forget to clear these variable when you clear the timer
Javascript Count Up Timer
JSFiddle
var original_date = currentDate();
var target_date = new Date('12/31/2020 12:00:00'); // Count up to this date
var interval;
function resetCountdown() {
original_date = currentDate();
}
function stopCountdown() {
clearInterval(interval);
}
function countdown () {
var current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - original_date;
if (current_date >= target_date) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
interval = setInterval(countdown, 1000);
};
How to create countup timer with keyboard events in js
I checked your code and found it needs too many changes.
- You are using
state
andisFired
as variables only but you need their persisted values on rerendering. Therefore, these must be states. - You are not unbinding the same listener which you binded on
keyup
andkeydown
. - As per your current code, your timer will start on 1st
keyup
and then nextkeydown
it will stop as such where it was. Now, on nextkeydown
it will reset to 0 and then onkeyup
, again timer will start from 0.
I modified your code and see working changes here,
https://codesandbox.io/s/xenodochial-shannon-im8zt?file=/src/App.js
Timer - Count up timer for Angular 8
I would do this by writing a function to return the difference between the current time and the creation time of an object.
My initial thought was to return the difference as a Date
object and then format the result. I soon ran into problems when formatting different time spans, as a date is not the same thing as a time span.
So instead of trying to format a Date
that is pretending to be a time span, I would create my own interface.
export interface TimeSpan {
hours: number;
minutes: number;
seconds: number;
}
By doing this we retain control of how time spans >= 1 day are handled, and avoid time zone issues.
I would use OnPush
change detection to keep control over when change detection is run:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
constructor(private changeDetector: ChangeDetectorRef) {}
}
I would then kick off an RxJS interval
in ngOnInit()
, making sure to unsubscribe when we're finished:
private destroyed$ = new Subject();
ngOnInit() {
interval(1000).subscribe(() => {
this.changeDetector.detectChanges();
});
}
ngOnDestroy() {
this.destroyed$.next();
this.destroyed$.complete();
}
The HTML would then get the elapsed time from a function on my component:
getElapsedTime(entry: Entry): TimeSpan {
let totalSeconds = Math.floor((new Date().getTime() - entry.created.getTime()) / 1000);
let hours = 0;
let minutes = 0;
let seconds = 0;
if (totalSeconds >= 3600) {
hours = Math.floor(totalSeconds / 3600);
totalSeconds -= 3600 * hours;
}
if (totalSeconds >= 60) {
minutes = Math.floor(totalSeconds / 60);
totalSeconds -= 60 * minutes;
}
seconds = totalSeconds;
return {
hours: hours,
minutes: minutes,
seconds: seconds
};
}
This function starts off by getting the total number of seconds elapsed since the creation date, and then works out the hour, minute, and second components.
Where entry
is the object that contains some Date
instance indicating its creation time. For my demo, I am using this interface:
export interface Entry {
created: Date;
id: string;
}
The elapsed time span can then be retrieved for each instance inside an *ngFor
like this:
<span *ngIf="getElapsedTime(entry) as elapsed">
{{elapsed.hours}} h {{elapsed.minutes}} m {{elapsed.seconds}} s
</span>
DEMO: https://stackblitz.com/edit/angular-p1b9af
Reset a Count Up Timer in Javascript
Basically, you have a global variable somewhere totalSeconds
which you need to also set back to zero when you reset.
var totalSeconds = 0; // reset this to zero when you reset as below
var secondsLabel = document.getElementById("seconds");
var minutesLabel = document.getElementById("minutes");
document.getElementById("reset").addEventListener("click",resertTimer);
setInterval(setTime, 1000);
function setTime(){
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function pad(val){
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
// reset() function
function resertTimer(){
document.getElementById("minutes").innerHTML = "00";
document.getElementById("seconds").innerHTML = "00";
totalSeconds = 0
}
<label id="minutes">00</label>
<label id="colon">:</label>
<label id="seconds">00</label>
<button id="reset">Reset</button>
How to write a countdown timer in JavaScript?
I have two demos, one with jQuery
and one without. Neither use date functions and are about as simple as it gets.
Demo with vanilla JavaScript
function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) { timer = duration; } }, 1000);}
window.onload = function () { var fiveMinutes = 60 * 5, display = document.querySelector('#time'); startTimer(fiveMinutes, display);};
<body> <div>Registration closes in <span id="time">05:00</span> minutes!</div></body>
Related Topics
Sorting Objects by Property Values
Clearrect Function Doesn't Clear the Canvas
How to Reset <Input Type = "File">
Reactjs Setstate() with a Dynamic Key Name
React.Js: Onchange Event for Contenteditable
Differencebetween Typeof and Instanceof and When Should One Be Used VS. the Other
Semicolon Before Self-Invoking Function
How to Put an Image File in a JSON Object
Fix Node Position in D3 Force Directed Layout
Why Does JavaScript Hoist Variables
Check If Option Is Selected with Jquery, If Not Select a Default
Leaflet Drawing Tiles Disjointly
Npm Install Cannot Find Module 'Semver'
Ignore Typescript Errors "Property Does Not Exist on Value of Type"