setInterval not working with content auto update - javascript

I'm trying to use this https://codepen.io/zeinab92/pen/xwWGWM
But It's not updating 'Hours, Minutes and Status' automatically without page reload.
How can I make it working so, times will automatically update and state text will also update based on the time condition whether it's Open or Closed.
I like the script except the auto update problem, I tried by create a new function,
setInterval(function() {
$("#timeDiv").html(data);
}, 1000);
by disabling default
setInterval(checkTime, 1000);
or setTimeout instead of setInterval
But no luck.

After debugging, I found the problem with the code.
You have declared now as global variable outside checkTime function and when page loads now variable stores value of new Date i.e the value of Date when page has been loaded. Hence the value of now is updated only once as global variable are executed only once.
Solution: Place the now variable inside checkTime so that each time it will have new value of Date whenever checkTime is called.
function checkTime(){
var now=new Date();
....
}
Hope this resolves the issue. (JS Fiddle)

Related

Nodejs getTime() only displays time of execution

I am working in a Nodejs application that is constantly running and I need to get the current system time every second. The problem is that is only displays the same time repeatedly rather than following the system time.
var date = new Date();
setInterval(function(){
console.log(date.getTime());
}, 1000);
This will just keep returning the exact same timestamp every second when I need it to return what the current system time is, in real time.
Well you should create new Date when function is executed. So this should work:
setInterval(function(){
var date = new Date();
console.log(date.getTime());
}, 1000);
What is the difference?
Well you created your date before execution of setInterval function. When function is executed you are getting time when object is created. In your example that is before calling setInterval function. In my example, date object is created every time when interval expire and function is called.
I hope that I have helped you.

Not able to update digital clock

I have to display respective time zone in digital format. The clock is displayed but it only updates after refreshing the page. Below is the code I used.
Below is my javascript code:
time: function() {
var zone = _.date.fleetTimeZone();
return moment().zone(zone).format('h:mm:ss a');
}.property('DS.session.last_fleet_interacted'),
Below is my handlebars:
<div class="time">{{time}}</div>
You'll need to turn time into a property, and update it each second, using setTimeout() or something. Then it'll work because of data binding (I assume Ember.js because tags).
Alternatively, just do a setTimeout() and re-render the time manually.

Coffeescript: Dynamically update time with moment js with coffeescript

I am having trouble dynamically seeing the time update with moment js. It shows the correct time but I have to refresh my browser to get the time update. I would like it to update it in real time. Like momentjs.com main page.
I've tried using setInterval and setTimeout but for some reason I get the below digits that don't even update.
Here's what I have so far code-wise. Pretty simple as far as moment goes and all I want is seconds to keep counting...
update = ->
time = moment().format('hh:mm:ss a')
clock = setInterval update, 1000
console.log(clock) //output: 53296
Any ideas are immensely appreciated.
You should put the output inside of the update method and everthing will work as expected.
The method setInterval won't return the result of the repeatedly called method but an identifier which can be used with clearInterval to stop the execution.
Just a small working example to print the time every seconds and stop after 10 seconds:
update = ->
console.log(moment().format('hh:mm:ss a'))
x = setInterval update, 1000;
setTimeout (-> clearInterval(x)), 10000
If you want to use that time as content of some DOM-Element you can use the following code inside your update function (assuming you have an element (e.g. div) with id "time"):
JQuery:
$("#time").text(moment().format('hh:mm:ss a'))
Plain JS:
document.getElementById("time").firstChild.data = moment().format('hh:mm:ss a')
Try this. If u are dont have to use meomentJS.
https://github.com/furkankaynak/countdown

Javascript setTimer

I'm having a hard time understanding the logic behind the setTimer method in javascript.
<html><head>
<script>
function Timer () {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
document.getElementById('show').innerHTML=h+":"+m+":"+s;
t = setTimeout("Timer()", 1000);
}
</script>
</head>
<body onload="Timer()">
<div id="show"></div>
</body></html>
setTimeout is used to delay a function/method execution. Then why it is being used in a real-time clock?
t = setTimeout("Timer()", 1000);
This part is confusing.
The clock is recursively calling itself, after the elapsed period of time.
Making a real-time clock is impossible in JS.
Because of how JS engines work, if you put Timer in a loop, to run for an infinite period of time, you'd never see the time update on the screen (as changes aren't drawn to the window until a function finishes and there's a gap in the program).
Also, inside that infinite-loop, it would be impossible to do anything else with the page (even closing it), because JS can only do one thing at a time, so it can't listen to any of the user's clicking until it's done with this loop.......
So that's what the setTimeout is for.
Timer is the function which acts as the clock.
Inside of the Timer function, at the end when all of the work is done, it's telling setTimeout to wait 1 second (1000ms) and then to call a function called Timer.
Timer just so happens to be the same function. But setTimeout doesn't know that, and doesn't care.
The t in this case is largely useless. setTimeout will return a number -- like taking a number at the doctor's office.
If, before you go through with it, you decide to back out, you can call clearTimeout(t); and it'll skip over that call (in this case, it would stop calling the clock).
There are a few bad-practices in here, that I figure I should mention, so that you can try not to copy them in your own practice.
First:
Pass setTimeout a reference to a function, and not a string...
var runThisFunction = function () { console.log("It's the future!"); },
time_to_wait = 250;
// DON'T DO THIS
setTimeout( "runThisFunction()", 250 );
// DO THIS
setTimeout( runThisFunction, 250 );
The difference is that setTimeout will run that string through eval, which can be a huge security concern depending on what you're trying to do.
The second problem is setting a random global variable, t... ...and hoping to use that as a solution.
First, in a couple of years, JS engines are going to start yelling at people for doing that stuff. Second, it's a huge hole, because any part of any app on that page could then overwrite t, or you could be relying on t somewhere else in your script, but every 1000ms, it gets written over with a new number.
Instead, they probably should have used a Timer.start(); and Timer.stop(); setup.
Your code:
t = setTimeout("Timer()", 1000);
The first thing you should know is that it's considered bad practice to put the first parameter in a string -- it should be the function name, unquoted, and without brackets, like so:
t = setTimeout(Timer, 1000);
That aside, your question about why it's being used to display a clock:
The use of setTimeout() inside the Timer() function to call itself is a common Javascript pattern to get a function to be called repeatedly. setTimeout() itself only triggers the function to be called a single time, after the given period of time has elapsed, so for a repeating event it needs to be re-triggered every time.
Since the setTimeout call is inside the Timer() function, it won't be set until Timer() is called the first time by some other means. This is where the body onload comes in.
As you suspect, setTimeout() isn't an accurate method for guaranteeing that a function will be called after exactly a given amount of time. Javascript is not multi-threaded, so any event handlers that are triggered must wait for any other code that is running at the same time. If something else is running slowly, this may cause your timer not to be triggered at exactly the moment it wants to be.
However, this isn't really a problem for your clock , because the clock is setting itself to the actual system time rather than relying on the setTimeout loop to keep itself in sync; the setTimeout loop is simply being used to make sure the display is updated (approximately) once a second. If it isn't actually quite exactly once a second, it doesn't really matter.
I hope that helps explain things a bit better.
When the Timer() function is called, it schedules itself to be run again one second later. The end result is once every second, Timer() updates the show element with the current time. (I have no idea why it's assigned to t, unless t is used in some other code on the page.)
The line starts The function again after one second.

edit javascript on the fly

I was curious how I might go about editing a variable on the fly, since whenever I try nothing happens. Take http://nyan.cat for example. I tried to edit the seconds variable, but nothing happened - why?
i used (in the JS console) seconds = 9001; RET and nothing happens....
That's because in http://nyan.cat/ the seconds variable is being set by the script repeatedly, based on the startTime Date object. In the specific case of http://nyan.cat/, to 'hack' the time, change the startTime.
Example: to increase your seconds by 1234567 seconds:
startTime = new Date(((+startTime/1000)-1234567)*1000);
What JS console are you using?In the firebug?
Here I tested it.
var seconds = 9001;
alert(seconds);

Categories

Resources