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
Related
I was creating a webpage and I would like to receive assistance in that. I need a text to popup when the UTCHours and UTCMinutes are equal to specific values. I want something like this. This is like the model , not actual code.
h = utcTime
m = utcminutes
if (h=x and m=y)
{
function myFunction();
}
Surely I wont do everything for you, but here you go. A base to start from.
// The button functionality
const $ = (x) => document.getElementById(x);
$('start').addEventListener('click', ()=>{
startTime();
});
$('stop').addEventListener('click', ()=>{
stopTime();
});
// The timer
// set variables
let date,
start,
stop;
function startTime() {
date = new Date(); // get current date.
start = date.getTime(); // get time from current date
// Just output
document.getElementById("showStart").innerHTML = start;
}
function stopTime() {
date = new Date(); // get current date.
stop = date.getTime(); // get time from current date
// just output
document.getElementById("showStop").innerHTML = stop;
document.getElementById("difference").innerHTML = stop-start;
}
jsfiddle
I was bored so here you go.
// The button functionality
const $ = (x) => document.getElementById(x);
$('setAlert').addEventListener('click', ()=>{
setAlert(3); // alert in x seconds.
});
// set variables
let date,
target,
stop,
interval = 1; // integer.
function setAlert(time) {
date = new Date(); // get current date.
target = date.getTime() + ( (time * 1000) - ((interval * 1000) +1000) ); // sets the time it should alert.
/*
* time -1 because it's a 1s interval, that means when it reaches x = y it will alert 1s later by the next "check". This why you need to subtract 1s.
* (time-1)*1000 is because the getTime returns time in ms not in seconds. You would need to make it setAlert(3000),
* i made it bit easier by multiplying the value by 1000 = ms.
*/
// The loop that checks time
setInterval(function(){ // This function makes the "checking each X ms"
if(stop !== target){ // Check if time was reached.
stopTime(); // Check time
}else{
alert("TIME IS OVER"); // When time is reached do this.
}
}, interval*1000); // Refreshes the time each second.
// Just output
document.getElementById("showTarget").innerHTML = target+(interval*1000); // Because the target time has "minus" in it (line 16) it needs to be added to show the real target time.
}
function stopTime() {
date = new Date(); // get current date.
stop = date.getTime(); // get time from current date
// just output
document.getElementById("showStop").innerHTML = stop;
// document.getElementById("difference").innerHTML = stop-target;
}
jsfiddle v2
function displayAlert(hour,minute){
//create a new Date Object(Current Date and Time)
var date = new Date();
// getUTCHours getUTCMinutes are inbuilt methods
// for getting UTC hour and minute by comparing it with timezone
var utcHour = date.getUTCHours();
var utcMinutes = date.getUTCMinutes();
//display alert when utc hour and minute matches sired time
if(utcHour == hour && utcMinutes == minute){
alert(utcHour + " : " + utcMinutes)
}
}
displayAlert(18,31)
setInterval(function(){
now = new Date();
hours = now.getUTCHours();
mins = now.getUTCMinutes();
executeFunctionIfEqualToDefined(hours, mins);
},60000); // this block will run every 60000 milli seconds i.e 60 seconds =1 min
function executeFunctionIfEqualToDefined(hours, mins){
if(hours === x && mins === y){
//execute your code here
}
}
Looking for a Script that will autho refresh page on scheduled local time clock.
Twise a day. Let's say at 8AM and 8PM,
every day, OR
specific week day, cush as Mon-Fri, Mon-Wed, etc.
Notice: recently, found below code and tried this but it doesn't not work. Looking for a proper script based on above description.
setInterval(function(){
var dt = new Date();
var clock_time = dt.getHours() + ":" + dt.getMinutes();
if ( clock_time === '22:10' ) {
location.reload();
}
You have left out the time in setInterval.
You can set 2 times using || (OR) operator.
let interval; // Use clearInterval(interval) to stop the interval
let refreshDelay = 60000; // Every minute
function scheduledReload() {
let dt = new Date();
let time = dt.getHours() + ":" + dt.getMinutes();
if(time ==='08:10' || time === '22:10') {
location.reload();
}
}
interval = setInterval(scheduledReload, refreshDelay);
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.
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
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 );