Issue with setInterval function call - javascript

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
);

Related

How to clear the previous interval and run a new one

I am very new in Node JS, my job is really simple: just clear the exiting interval and run a new on every user button click.
I've tried using global.clearInterval, but it didn't work
function time() {
if (today.getTime() === subuh.getTime()){
admin.messaging().sendToDevice(token, notifikasi)
}
console.log(today.toTimeString)
}
clearInterval(clock);
var clock = setInterval(time, 1000);
What I expect is var clock is cleared before setInterval
Please help me, help me solve this and make me sleep
I think you need two functions here: one will be called when the user clicks the button (I called it restart()) - it will clear the previous timer and start a new one. And the second function is what you actually want to be repeated every second and what you pass to the setInterval (I just log the current timer id).
Check out this example:
var timer;
function time() {
console.log('Timer ID:', timer);
}
function restart() {
clearInterval(timer);
timer = setInterval(time, 1000);
}
<button onclick="restart()">(Re)start</button>
Before your call to clearInterval(clock); the variable clock does not exist as such you should get a reference error of clock not being defined. You can however be able to clear value of clock after the call to set interval. this is because the variable clock only start existing after the call to set var clock = setInterval(time, 1000); Alternatively, you could define clock before you call clearInterval.
function time() {
if (today.getTime() === subuh.getTime()){
admin.messaging().sendToDevice(token, notifikasi)
}
console.log(today.toTimeString)
}
var clock;
clearInterval(clock);
clock = setInterval(time, 1000);
Either way, it is the same as doing this
var clock = setInterval(time, 1000); and clearing the interval at some point when some certain event occur.

javascript new Date() isn't updating

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);

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.

Javascript time passed since timestamp

I am trying to "cache" some information by storing it in a variable.
If 2 minutes have passed I want to get the "live" values (call the url).
If 2 minutes have not passed I want to get the data from the variable.
What I basicly want is:
if(time passed is less than 2 minutes) {
get from variable
} else {
get from url
set the time (for checking if 2 minutes have passed)
}
I've tried calculating the time with things like
if((currentime + 2) < futuretime)
but it wouldn't work for me.
Anybody know how to properly check if 2 minutes have passed since the last executing of the code?
TL;DR: Want to check if 2 minutes have passed with an IF statement.
Turning your algorithm into working javascript, you could do something like this:
var lastTime = 0;
if ( Math.floor((new Date() - lastTime)/60000) < 2 ) {
// get from variable
} else {
// get from url
lastTime = new Date();
}
You could put the if block in a function, and call it anytime you want to get the info from either the variable or the url:
var lastTime = 0;
function getInfo() {
if ( Math.floor((new Date() - lastTime)/60000) < 2 ) {
// get from variable
} else {
// get from url
lastTime = new Date();
}
}
Hope it helps.
If you want to do something on a timer in JavaScript, you should be using setTimeout or setInterval.
Having your code run in a continuous loop will cause your browser's VM to crash.
Using setTimeout is rather easy:
setTimeout(function(){
// do everything you want to do
}, 1000*60*2);
This will cause the function to run in at least two minutes from the time the timeout is set(see this blog post from John Resig for more deatils). The second argument is the number of milliseconds, so we multiply by 60 to get minutes, and then 2 to get 2 minutes.
setInterval, which follows the same syntax will do something EVERY x milliseconds.
Without using 3rd party libs, just use Date.getTime() and store it as some variable:
var lastRun = null;
function oneIn2Min() {
if (lastRun == null || new Date().getTime() - lastRun > 2000) {
console.log('executed');
}
lastRun = new Date().getTime();
}
oneIn2Min(); // prints 'executed'
oneIn2Min(); // does nothing
oneIn2Min(); // does nothing
setTimeout(oneIn2Min, 2500); // prints 'executed'
You can also opt to make some simple object out of it (to keep your code organised). It could look like this:
var CachedCall = function (minTime, cbk) {
this.cbk = cbk;
this.minTime = minTime;
};
CachedCall.prototype = {
lastRun: null,
invoke: function () {
if (this.lastRun == null || new Date().getTime() - this.lastRun > this.minTime) {
this.cbk();
}
this.lastRun = new Date().getTime();
}
};
// CachedCall which will invoke function if last invocation
// was at least 2000 msec ago
var c = new CachedCall(2000, function () {
console.log('executed');
});
c.invoke(); // prints 'executed'
c.invoke(); // prints nothing
c.invoke(); // prints nothing
setTimeout(function () {c.invoke();}, 2300); // prints 'executed'
If you're open to include 3rd party libs this might be very handy in other tasks too:
http://momentjs.com/docs/#/manipulating/add/
You can do something like that
var myVal = {
data: null,
time: new Date()
}
function getMyVal () {
if(myVal.time < new Date(new Date().getTime() - minutes*1000*60)) {
myVal.data = valFromRequest;
myVal=time=new Date();
}
return myVal.data;
}

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