Jquery set counter, but reset when function is called - javascript

Does anyone know what function would be best to use for the following scenario?
When a song starts playing, I want to start a 'stopwatch' that counts up in seconds.
At any point, i'd like to be able to call this variable, such as a button that you click that'll do alert(time) and reveal the count on the timer.
But, when i run a function reset-timer(); I'd like this all to reset and start counting again.
I was thinking settimeout or setinterval but not sure which is correct.
Thanks :)

Here is a basic concept to get you started:
http://jsfiddle.net/V29qK/1/
var startTime = new Date();
function SetTime(){
var curTime = new Date();
var seconds = Math.round((curTime - startTime) / 1000) + " second(s)";
document.getElementById("timer").innerHTML = seconds;
}
var interval = setInterval(SetTime, 1000);
function ResetTime(){
document.getElementById("timer").innerHTML = "0 second(s)";
startTime = new Date();
}
​
The logic is: Set a global variable to a new Date() to signify the Start Time. On an interval (or timeout), get the current new Date() and subtract the Start Time from it. This will give you the difference in milliseconds. You can then update whatever UI element you want with this data.
To "Reset" the timer, you simply set the Start Time to the current time with new Date()

Related

Reseting a variable value everyday at midnight in node js

I have a global var in my node js code. I need to reset its value to 1 everyday midnight at 12am. How is it done in node js?
I have read certain articles about node scheduler. Does it work or there are any other ways?
You can use a simple setTimeout() to schedule it yourself:
let myVar = 10;
function scheduleReset() {
// get current time
let reset = new Date();
// update the Hours, mins, secs to the 24th hour (which is when the next day starts)
reset.setHours(24, 0, 0, 0);
// calc amount of time until restart
let t = reset.getTime() - Date.now();
setTimeout(function() {
// reset variable
myVar = 1;
// schedule the next variable reset
scheduleReset();
}, t);
}
scheduleReset();
Any time your program starts, it can just call scheduleReset().
FYI, I lifted most of this code from a program I wrote (on a Raspberry Pi server) that restarts itself at 4am every night and that program has been doing that successfully for several years.
Using node-schedule this should be straightforward. Define your job with the correct cron-tab and reset the variable to the default value in the scheduleJob-callback:
const schedule = require('node-schedule');
let yourVar = 12345;
const globalResetJob = schedule.scheduleJob('0 0 * * *', () => {
yourVar = 1;
});

Javascript setInterval function clock dependent instead of load dependent

Is it possible to start setInterval counter clock dependent instead of load dependent?
Assuming that every computer has the minutes of the clock always at the same time.
If I open the page at 12:01 and I want a set interval of 2 minutes that always start from 12:00 (or any other hour but at :00 minutes). I want the event to fire at 12:02, 12:04 etc. no matter when I load the page or if it was open or not at 12:00.
The answer can be in jquery too.
You could take the delta to the next wanted slot and adjust with it the timeout.
function out(k, v) {
console.log(k.toString().padEnd(8), v.toString().padStart(15));
}
var time0 = new Date().getTime(),
slot = 2 * 60 * 1000,
time1 = Math.floor(time0 / slot + 1) * slot,
delta = time1 - time0;
out('slot', slot);
out('delta', delta);
out('time0', time0);
out('time1', time1);
setTimeout(function () {
var time2 = new Date;
out('time2', time2.getTime());
out('real', time2.getTime() - time0);
console.log(time2.toISOString());
}, delta);

Updating time without refreshing the page with Javascript

I'm building an app that displays the current time without have to refresh.
I'm calling the time below, but when I display it I have to refresh the page to update the time. How do I continuously update the time?
function GetTime(){
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();
if (hour>=12){ //Adding endings
suffix = "P.M.";}
else{
suffix = "A.M.";}
minute = addZero(minute); //Call addZero function
hour = removeMilitary(hour); //Call removeMilitary Function
var fullTime = hour + ":" + minute + " " + suffix; //Combine hour minute and the suffix
function addZero(number){
if (number<10){
number = "0" + number;
}
return number;
}
function removeMilitary(hour){ //This function can be removed if desired by user.
if (hour > 0 && hour <= 12) {
hour = "" + hour;
} else if (hour > 12) {
hour = "" + (hour - 12);
} else if (hour == 0) {
hour= "12";
}
return hour;
}
return fullTime;
}
Javascript has a setInterval method.
You can get the time every second, by running your program every 1000 milliseconds:
setInterval(GetTime, 1000);
//if you incorporate updating the html
//within the getTime function
or
setInterval(function(){
document.getElementById("ID_of_the_time_element").innerHTML= getTime();
//do something else
}, 1000}
Why setInterval at 1000 ms isn't very accurate
The problem with that is unless you start the set interval exactly on the second, your program will not change the second exactly on the second. I would recommend you get it more accurate by adjusting the interval to every 100 ms, for example. Then it would update every 100ms, which means that the most your clock will be behind is a tenth of a second.
A better solution
Setting an interval every 100ms is ok, but if you want more accuracy, setting it to 10ms isn't necessarily the best option, because repeating a task every 10ms is a pretty large burden on the computer. You could also use find the number of ms until the next second, and then use the setTimeout method to wait until the next second arrives and start the set timeout then. You would still have some computational delay(the amount of time between when it gets the number of milliseconds until the next second and it starts the setTimeout), but that's probably a lot less than 100 ms.
I assume you will use the setInterval() function.
just add this to your button onclick;
setInterval(function(){Document.getElementById("div").innerHTML = getTime},1000);
setInterval (GetTime, 1000) will call your function every second (1000 milliseconds) to get the time. You don't show how you're putting the time on the page, so you'll need to incorporate that as well.
UPDATE I forgot the setInterval but someone else already pointed at it, so mix both answers and you're done!
Look at getElementById and innerHTML.
Something like the following snippet at the end of your function (instead of return fulltime ) should work:
...
var myElement = documentGetElementById('mydiv');
myElement.innerHTML = fulltime;
...
Of course you need to define some HTML element with <div id="mydiv"></div> or whatever you choose.

javascript compare current time to variable every minute

I have a start date defined in a database and I need to know when the start date is greater then the current time. I've tried using setInterval, but I can't access the updated time outside the setInterval function.
This is what I need to compare the current time to the database variable:
if(startDate > now) {
var status = 'pre';
}
I've tried using setInterval as follows, but I can't access the updated (current time) outside of the setInterval function.
setInterval(function(){
now = moment(new Date()).format();
console.log('time1 ', now); // this works
}, 1000);
console.log('time2 ', now); // this doesn't
What am I doing wrong?
Try this..
var now = new Date();
setInterval(function(){
now = new Date();
console.log('time1 ', now.getHours()+":"+now.getMinutes()+":"+now.getSeconds());
}, 1000);
console.log('time2 ', now.getHours()+":"+now.getMinutes()+":"+now.getSeconds());
});
I ended up using react-interval https://github.com/nkbt/react-interval to accomplish this.

Prevent the timer from resetting [duplicate]

This question already has an answer here:
Countdown timer resets on page refresh
(1 answer)
Closed 8 years ago.
I'm making a countdown timer script that exits the program when the time reaches 0.
The problem is that when the page reloaded the timer starts again from the beginning..
Is there any way to prevent the timer from resetting?
// set the date we're counting down to
var target_date = new Date().getTime();
var delay=100;
// variables for time units
var days, hours, minutes, seconds;
// get tag element
var countdown = document.getElementById("countdown");
// update the tag with id "countdown" every 1 second
setInterval(function () {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (current_date - target_date) / 1000;
var a=(delay-seconds_left);
// do some time calculations
minutes = parseInt(a / 60);
seconds = parseInt(a % 60);
var progress = a/delay*100;
// format countdown string + set tag value
countdown.innerHTML = '<div Class=outer style="font-size:20px;width:'+progress+'%">'+minutes + "m: " + seconds + "s" + '</div>';
if(a <= 0)
{
window.open("a.html")
self.close();
//var wind = window.open("a.html");
}
}, 1000);
You can store target_date in local storage (or a cookie) and look for it on page load. E.g.:
var target_date = localStorage.target_date;
if (target_date) {
// Found it in local storage, turn the string into a number
target_date = parseInt(target_date);
} else {
// Didn't find it in local storage, get the target and
target_date = new Date().getTime(); // See below, this looks weird
localStorage.target_date = String(target_date);
}
Local storage is quite well-supported in modern browsers.
Note that only strings and certain other storage-compatible items can be stored in local storage, which is why I'm explicitly dealing with a string version of the number above. If you need to store more complex information, JSON is usually a useful format.
Your code initializing target_date doesn't make much sense to me: It grabs the time now. I would expect a countdown to grab a time in the future for target_date. In any case, replace that line (or replace what you're storing) as necessary.
Alternatively you could always put the current time into a cookie and load that cookie when loading the page.
Learn more about Cookies here.

Categories