javascript new Date() isn't updating - javascript

function doSomething(){
var rightNow = new Date();
}
doSomething();
if my machines' date is 11:59am, after 1min it will be the next day, why am I still seeing it's 3 Jan?

Every time you call doSomething(), you make a new instance of Date() right when you call it. It won't change until you call it again. If you want it to change every second, try this:
setInterval(function() {
console.log(new Date);
}, 1000);

Related

How to dynamically pass the different time on setInterval() method in react js

Code :
class Schedule extends Component {
state = {
new_date: null
}
componentDidMount() {
var start = new Date().getMinutes()
var end = 24
var diff = end - start
var interval = setInterval(() => {
this.setState({
new_date: new Date()
})
}, diff)
interval()
}
}
Here all i want is to pass different timer value on each page refresh or specific condition is satisfied
Suppose when i refresh the page i will have new date and i want to subtract new date from end and here i can get suppose diff == 5000 millisecond.
But the problem is after the timer has executed i want to again find new date in the variable start and substract it from variable end so that i will have different value in variable diff and thus different timer value and above code cannot update the value of variable start.
It would be great help if somebody could help me out
You should clear interval if you want to change the time
let interval
class Schedule extends Component {
runInterval: (time) => {
if (interval) {
clearInterval(interval)
interval = null
}
interval = setInterval(() => {
// do something in here and you have also a new time
// pass new time to run interval function to have interval with new
// time
this.runInterval(3000) // 3000 is an example of a new time
}, intervalPeriod)
}
componentDidMount() {
var start = new Date().getMinutes()
var end = 24
var diff = end - start
this.runInterval(diff)
}
}
you need to use setTimeout and in this timeout call again setTimeout with different time value
var time = 1000;
function recursion(){
time = 2000;
setTimeout(function(){
recursion();
},time);
}
recursion();

JavaScript Countdown Timer Code [JS]

I'm currently trying to get a countdown timer working but, I don't know JavaScript at all.
<script>
$(document).ready(function (e) {
var $timer = $("#timer");
function update() {
var myTime = $timer.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$timer.html(ts[1]+":"+ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
</script>
But I've stumbled upon a problem. So I want it to stop on 00:00, but it continues going.
Also at 2 minutes left and no time remaining I want it to execute some code.
At no time remaining (00:00) I want it to simply redirect to a page and at 2 minutes remaining I want it to run some custom code (Which I have).
But I have no idea on how to make it run at a time and make it stop at a time.
Can anyone help me with this?
Try
$timer.html(ts[1]+":"+ts[2]);
if((ts[1]==="02") &&(ts[2]==="00")){
//custom code at 02:00
}
if((ts[1]==="00") &&(ts[2]==="00")){
//Make the redirect
}
else{
setTimeout(update, 1000);
}
DEMO
The inner function should be a sybling of the anonymous function. Right now update(), can't be called because you are using setTimeout() -> update() should be on the same level as your anonymous function.

Detect when Date().getSeconds() has a new value

I want to detect a change in the value of Date().getSeconds() as soon as it happens.
I currently use:
function updateClock {
....
}
function detectChange(previousSec) {
var currentSec = new Date().getSeconds();
if (previousSec !== currentSec) {
updateClock();
}
}
setInterval(function () {
var dat = new Date();
var sec = dat.getSeconds;
detectChange(sec);
}, 10);
Is there a better way to do this?
Thanks!
How about a 2-step process?
First, align your clock with the system's 0-millisecond mark
setTimeout(startClock, 1000 - (new Date()).getMilliseconds());
Then, you only need to tick once per second
function startClock() {
setInterval(function do_your_thing() { ... }, 1000);
}
Practical demonstration (jsfiddle) shows that even if you do a large amount of work during the cycle, this method is pretty stable. In fact, on my machine you get better precision than the ±16ms resolution typically achievable in desktop task schedulers.
Unfortunately there is no standard event that fires when the clock changes seconds, so you'll need to set up an interval to detect it.
Setting an interval for every 1000ms means your clock could be off by almost a full second. Therefore I can understand why you'd want to check the seconds more than just once per second. The core concept here is sampling rate. The faster we sample the more precise we are, but the more processing time we waste detecting changes.
I think this will work for you.
function updateClock (date) {
console.log(date);
};
(function () {
var oldDate = new Date();
return setInterval(function () {
var date = new Date();
if (date.getSeconds() != oldDate.getSeconds()) {
updateClock(date);
}
oldDate = date;
}, 10); // precision is ~10ms
})();
It will have a new value after every one second, therefore just put a timer with 1 second interval.

Issue with setInterval function call

I'm trying to call the setInterval function in my pop up window to update the time every second but when it is called my HTML page doesn't update at all just shows the initial time upon loading. I can't see what I'm doing wrong with this code.
var currentTime = new Date();
window.self.setInterval(
function()
{
window.self.document.getElementById("Time").innerHTML = currentTime.toTimeString();
}, 1000 );
Any reason why this is happening?
currentTime is being set once and only once. You need to create a new Date object at every interval. Something like this:
setInterval(
function()
{
document.getElementById("Time").innerHTML = (new Date()).toTimeString();
},
1000
);

Putting a setInterval when a function called

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 1, 20, 00, 0) - now;
function openAPage() {
var startTime = new Date().getTime();
var myWin = window.open("http://google.com","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;
document.write("<br>button pressed#</br>")
document.write(startTime);
document.write("<br>page loaded#</br>")
document.write(endTime);
document.write("<br>time taken</br>")
document.write(timeTaken);
myWin.close()
}
function beginSequence() {
openAPage();
setInterval(openAPage, 5000);
}
setTimeout(beginSequence, millisTill10);
This is my JS code. I am opening a web page with setTimeout as you see. But after then I want to put an internal for example I will call openAPage function every 1 minute after setTimeout statement. How will I do it? Can anyone fix my code?
setTimeout(startOpeningPages, millisTill10);
function startOpeningPages() {
openAPage();
setInterval(openAPage, 60 * 1000);
}
I realize there are a lot of correct answers already. I'll post this anyway for kicks :)
function() {
var win = window.open("about:blank")
var doc = win.document
doc.write("Hello")
setTimeout(arguments.callee, 60*1000)
}()
These are 2 of the my favorite things you can do in Javascript: Self-invoke a function (the ending () after the function declaration, and being able to access the anonymous function from within the function through arguments.callee.
This is better than setInterval in that the first process has to be completed and then 60s later, the second process starts. With setInterval, the process just keeps starting every 60s. 60s is a large interval where this wouldn't matter as much, but this usually matters a lot more with smaller times (in the ms ranges). Because it might end up buffering the second function to execute before the first one is complete.

Categories