Momentjs and countdown timer - javascript

I found the Momentjs library which is pretty cool, however I don't find the documentation to be very clear on how to achieve some simple tasks.
I'm trying to build a countdown timer and I'm guessing I should use the duration object, but I don't quite understand how (maybe due to the fact that English isn't my first language). Anyways this is what I want:
var time = 7200;
var duration = moment.duration('seconds',time);
setInterval(function(){
//show how many hours, minutes and secods are left
$('.countdown').text(duration.format('h:mm:ss'));
//this doesn't work because there's no method format for the duration object.
},1000);
So everysecond it should display:
02:00:00
01:59:59
01:59:58
01:59:57
...
00:00:00
How would I achieve this result with the Momentjs library?
Thanks!

duration object represents a static period, and it does not increase/decrease with the flow of time. So if you what to decrease it you have to do it yourself, for example creating a kind of a seconds counter or recreating duration object every time. Here is the code for the second option:
var time = 7200;
var duration = moment.duration(time * 1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
//show how many hours, minutes and seconds are left
$('.countdown').text(moment(duration.asMilliseconds()).format('h:mm:ss'));
}, interval);

I don't know Momentjs very well either, but I think you are looking for something like this:
var time = 7200;
var duration = moment.duration('seconds',time);
setInterval(function(){
var countdown = duration.milliseconds();
$('.countdown').text(moment(countdown).format('h:mm:ss'));
},1000);

https://github.com/jsmreese/moment-duration-format
Its a plugin to the Moment.js JavaScript date library to add comprehensive formatting to Moment Durations
<script type="application/javascript" src="/js/moment.js"></script>
<script type="application/javascript" src="/js/moment-duration-format.js"></script>
<script>
function startTimer(){
var duration = moment.duration({
'hour': 2,
'minutes': 0,
'seconds': 0
});
var interval = 1;
var timerID = -1; //hold the id
var timer = setInterval(function () {
if(duration.asSeconds() <= 0){
console.log("STOP!");
console.log(duration.asSeconds());
clearInterval(timerID);
}
else{
duration = moment.duration(duration.asSeconds() - interval, 'seconds');
$('.countdown').html( duration.format("hh:mm:ss", { trim: false }) );
}
}, 1000);
timerID = timer;
return timer;
};
//start
myTimer = startTimer();
//stop
//clearInterval(myTimer);
</script>

Here is what I did in 2019.
var time = 7200;
var duration = moment.duration(time, "seconds");
var interval = 1000;
setInterval(function(){
duration.subtract(interval, "milliseconds"); //using momentjs substract function
console.log(moment(duration.asMilliseconds()).format('hh:mm:ss'));
}, interval );

Related

Moment.js countdown not decrementing more than a second

I'm using moment.js to create a three minute countdown. However, every time the page loads, the timer decrements by one second and stops at 2:59. Printing out variables such as future and difference seems to yield normal results, however, so I believe that my error lies in the countdown. What is wrong with my countdown?
Here's my code:
<script type="text/javascript">
$(document).ready(function(){
var now = moment();
var future = moment(now).add(3, 'm');
var difference = future - now;
var duration = moment.duration(difference, 's');
var interval = 1000;
setInterval(function() {
if(duration.asSeconds() <= 0) {
clearInterval(intervalId);
document.getElementById("clock").innerHTML = moment(duration.asSeconds()).format("m:s");
}
duration = moment.duration(duration.asSeconds() - 1, 's');
document.getElementById("clock").innerHTML = moment(duration.asSeconds()).format("m:s");
}, interval);
});
</script>
you can change that to be something like this:
if (moment.duration(future - moment()).asSeconds() <= 0) {
and change
duration = moment.duration(duration.asSeconds() - 1, 's');
to be
duration = moment.duration(moment.duration(future - moment()).asSeconds(), 's');
because you're closure is capturing the value of duration above but never really updating it.

How do I make a Javascript timer where the number starts at 700000000 and counts down by 2.5 per 1 second

I'm trying to make a timer that functions like the one on this website: http://www.gaiacoin.com/ The timer starts at 7 Billion and counts down at a rate of 2.5 points per second.
How should I write this Javascript function?
Thanks!
in javascript the function setInterval will call a specific function every X milliseconds based on the 2nd parameter.
var myNumber = 7000000000;
var myInterval = setInterval(function(){
myNumber -= 2.5;
},1000);
the 1000 is miliseconds.. so.. 1000 miliseconds per second.
You would use the setInterval function to create the timer, and then use getElementById to find the spot in the HTML document to write the text.
var x = 7000000000;
setInterval(function() {
x = Math.max(0, x - 2.5);
document.getElementById("field_name").innerHTML = "Gaiacoin Clock " + x;
}, 1000);
Ignore all the down votes. Everyone that has down voted your question at some point didn't know the answer either, and how do we learn unless we ask for help.
Here's how I'd do it
var startValue = 7000000000;
// arbitrarily started at midnight 7th November 2015 UTC
// change to whatever you want,
// or even read something from a cookie if you want
var startTime = new Date(2015, 10, 7, 0, 0, 0);
var perSec = 2.5;
var beginOffset = new Date() - startTime;
var startPerform = performance.now();
var displayValue;
var go = function() {
var elapsed = beginOffset + (performance.now() - startPerform);
var value = Math.floor(startValue - perSec * elapsed / 1000);
if(value != displayValue) {
console.log(displayValue = value); // do your output here
}
}
setInterval(go, 100);

Javascript: restarting countdown timer doesn't work as I expect it to

I am making a countdown timer that should be reseting and starting anew every 10 seconds.
This is the code I came up with by now:
function count(){
var end_date = new Date().getTime()+10*1000;
setInterval(function(){
var current_date = new Date().getTime();
var seconds_left = parseInt((end_date - current_date) / 1000);
document.getElementById("countdown").innerHTML = seconds_left + " seconds ";
}, 1000);
}
setInterval(function(){count()}, 10*1000);
It is supposed to function as follows:
+ I set interval that will restart count() every 10 seconds.
+ count() defines end_date - a date 10 seconds from now.
+ then count() sets interval that will restart every 1 second.
+ every 1 second seconds_left variable is changed according to how current_date changed with respect to end_date.
+ as soon as seconds_left becomes 0, setInterval from step 1 fires and starts count() anew.
Which step am I implementing the wrong way? Do I misunderstand the functioning of setInterval()?
Here is my JsFiddle: http://jsfiddle.net/sy5stjun/ .
My guess is that each call is in its own new object and you get multiple instances of itself fighting ever 10 seconds.
Using your approach using date objects here is a possible re-write:
var tmr = null;
var time;
function bigInterval() {
clearInterval(tmr);
time = (new Date()).valueOf() + (10 * 1000);
smallInterval();
tmr = setInterval(smallInterval, 500);
}
function smallInterval() {
var cur = (new Date()).valueOf();
var seconds_left = parseInt((time - cur) / 1000);
document.getElementById("countdown").innerHTML = seconds_left + " seconds";
}
bigInterval();
setInterval(bigInterval, 10*1000);
In the above code I've updated the small timer to be 500ms instead of 1000ms as it won't exactly line up with the system clock at 1000 and you get visual jumps in the numbers.
If exact timing isn't 100% important then here is a possible shorter method:
var t = 10;
setInterval(function() {
document.getElementById("countdown").innerHTML = t + " seconds";
t--;
if (t <= 0) {
t = 10;
}
}, 1000);
There are a few things going on, here. You're not specific why you have to set another interval inside your loop, but there are a lot easier ways to accomplish what you're going for. Another approach follows:
HTML:
<!-- string concatenation is expensive in any language.
Only update what has to change to optimize -->
<h1 id='countdown'><span id="ct"></span> seconds </h1>
JS:
// For one thing, grabbing a new reference to the
// dom object each interval is wasteful, and could interfere with
// timing, so get it outside your timer, and store it in a var scoped
// appropriately.
var ct = document.getElementById("ct");
// set your start
var ctStart = 10;
// set your counter to the start
var ctDown = ctStart;
var count = function() {
// decrement your counter
ctDown = ctDown - 1;
// update the DOM
ct.innerHTML = ctDown;
// if you get to 0, reset your counter
if(ctDown == 0) { ctDown = ctStart; }
};
// save a reference to the interval, in case you need to cancel it
// Also, you only need to include a reference to the function you're
// trying to call, here. You don't need to wrap it in an anonymous function
var timer = window.setInterval(count, 1000);
My jsFiddle available for tinkering, here: http://jsfiddle.net/21d7rf6s/

Javascript: Execute a function for every 3 seconds for One minute

I need to execute a function for every 3 sec upto 1 minutes. This should be called when a user focus on the input box.
I have tried by Googling but most of them come-up with setInterval function. I knew that the setInterval can be used to call a function for certain time interval. But i need to stop that if the time reaches 1 min.
Please suggest me on this.
Try this on input focus of textbox:
var startTime = new Date().getTime();
var interval = setInterval(function(){
if(new Date().getTime() - startTime > 60000){
clearInterval(interval);
return;
}
//do whatever here..
}, 3000);
Working Demo
Demo Code:
$('input').one('focus',function(){
var startTime = new Date().getTime();
var interval = setInterval(function(){
if(new Date().getTime() - startTime > 60000){
clearInterval(interval);
alert('interval cleared');
return;}console.log('test')}, 3000);})
Try like this -
var time = 0;
var interval = setInterval(function(){
// do your stuf
time += 3000;
if(time >= (1000*60)){ // one minute
clearInterval(interval);
}
},3000);
Working Demo

Countdown Timer for every 6 hours

Just wondering, if there is any way or codes, that can set countdown timer for every 6hours, for everyday?
For example, i want to start countdown at this timing(In other words, like every 6 hours):
9am-3pm
3pm-9pm
9pm-3am
3am-9am?
I have look all over the site, and couldn't find a countdown timer like that..
Preferably in HTML and javascript/jquery.
var timer = {
started: false,
timestamp: 0
},
trigger = 15; //3pm
function timerInit(){
var hour = new Date().getHours();
if(!started && hour === trigger){ //When it's 3pm, the timer will start
startTimer(); //└─ rewrite the conditional statement
// as needed
//do whatever you want here
timer.timestamp = +new Date();
timer.started = true; //Indicates the timer has been started
}
requestAnimationFrame(timerInit); //setTimeout is not efficient
}
requestAnimationFrame(timerInit);
//This is for when the timer has ended.
function timerEnded(){
timer.started = false;
}
function startTimer(){
var d = new Date();
timePassed = new Date(timer.timestamp + 1000*60*60*6 - d);
var remaining = { //Calculate time difference
hour: timePassed.getHours(), // using timestamps
minute: timePassed.getMinutes(),
second: timePassed.getSeconds()
}
console.log(remaining);
if(timePassed > 0){
setTimeout(startTimer, 500); //Countdown
}else{
timerEnded(); //Ended
}
}
http://jsfiddle.net/DerekL/kKPcr/7/
You can use javascript's native setInterval method
E.g:
var timer = setInterval(myfunction, 21600) // 21600 seconds == 6 hours

Categories

Resources