I can't get current millisecond in Javascript - javascript

I can't get updated (current) time as milliseconds below. Even if I reassign the system time inside of the loop, the functionality does not work as I aimed. I'm kinda new about using JavaScript. So I was trying to convert below Java code to JavaScript. What is the problem in my JS code could you help me please?
My purpose with this function: Make system wait until the value becomes not null
Current result -> Time difference does not change per given check interval
waitUntilValueComes(value, timeout, checkInterval) {
let currentTime = new Date().getMilliseconds()
cy.log('Current time ' + currentTime)
let diff = new Date().getMilliseconds()- currentTime
while (timeout > (diff)) {
cy.log('Date time ' + diff)
if (value != null) {
break
}
cy.wait(checkInterval)
diff = new Date().getMilliseconds()- currentTime
}
}
Java Code that I tried to transform into JS
public void waitUntilValueComes(String value, long timeout, long checkInterval) throws InterruptedException {
long currentTime = System.currentTimeMillis();
while (timeout > System.currentTimeMillis() - currentTime) {
if (value!= null)
break;
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(checkInterval));
}
}

You can try the Date.now() Global object and method which gets the current time with milliseconds but in unix timestamp however its a little inaccurate compared to the 2nd method in firefox browsers as per the MDN Docs
The first method is what you need if you need the time stamp
The second method is the same as the method you used
Just assign a new const newDate = new Date();
Call that const with .getMilliseconds() method
assign that to a new const dateMS = newDate.getMilliseconds();
Debug the dateMS variable we just assignedconsole.log(dateMS);
const dateNow = Date.now();
console.log("dateNow is:" + dateNow);
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
//FOR YOUR OLD METHOD JUST ASSIGN A VARIABLE for the new date
const newDate = new Date();
const dateMS = newDate.getMilliseconds();
console.log("Date in milli seconds is" + dateMS);
W3School JavaScript Date Methods

Related

JS How to keep counting the time

I just started learning Javascript a month ago. I would like to know how to keep counting and updating and showing it in real-time.
var date = new Date();
var second = document.querySelector('#sec')
var time = document.querySelector('#future-time')
function currentTime(){
console.log('a')
time.innerHTML = date;
second.innerHTML = date.getSeconds();
}
setInterval(currentTime, 1000);
with this code, I can see the time on the page but then, the second doesn't update so it keeps saying the same second with console.log(). The current time on the page doesn't go forward. Please help me.
The issue you're running in to is that once you assign var date = new Date() then date will always be the datetime as of that exact time it was assigned. You can instead create a new Date object each time you call currentTime and you'll get a refreshed Date object current as of the time the function is called.
var second = document.querySelector('#sec')
var time = document.querySelector('#future-time')
function currentTime(){
var date = new Date();
time.innerHTML = date;
second.innerHTML = date.getSeconds();
}
setInterval(currentTime, 1000);
<span id="sec"></span>
<span id="future-time"></span>

how timer count down in this example ? how date which represent new Date().getTime() is greater than nextDate ? could any one explain that pls?

how date is greater than nextDate ??
could any one explain clearly how this code works ?
const controlTime = () => {
let second = 1000
let date = new Date().getTime()
let nextDate = new Date().getTime() + second
let interval = setInterval(() => {
date = new Date().getTime()
if (date > nextDate) { // how date is greater than nextDate ??
setDisplayTime((prev) => {
return prev - 1
})
nextDate += second // how it will be as a result ???
}
}, 30)
}
Firstly, the function setDisplayTime and the var prev aren't included in your code, so I can't explain that with accuracy, but I can infer from the function name that that it changes a display time somewhere in the UI.
However, for the other aspects of your question:
date will become greater than nextDate eventually because during the setInterval function the date variable is mutated or updated to the current time every 30 milliseconds (not seconds as you say in your comment, timers in JS work in milliseconds). The nextDate is only updated when the ever-increasing date variable then exceeds the current value stored in nextDate.
nextDate += second is a short hand increment calculation for nextDate = nextDate + second. This code adds one second (or 1000 milliseconds as set in the second varible) to nextDate and resets this same variable with the updated value. Thus making it once again greater than date and so our check runs again every 30 milliseconds and repeats for as long as the code is running.

How can I use a while loop to generate a delay between console logging one item and another item?

I have the following code but it doesn't seem to work. I want to log to the console "dark-green", have it wait a couple milliseconds, then log "light-green", all WITHOUT using setInterval or setTimeout. Is this possible with javascript?
function logGreen() {
console.log("dark-green");
wait(200);
console.log("light-green");
}
function wait(ms) {
var time = new Date();
var milliseconds = time.getMilliseconds();
var startTime = milliseconds;
var currentTime = milliseconds;
while(currentTime - startTime < ms) {
currentTime = milliseconds;
}
}
The problem I am running into is that the the loop breaks the browser so to speak, and I'm not sure how to fix this. Is there a way to do this with a for loop?
The issue with your code is that the value of currentTime is not being updated properly in your while loop.
The code inside your while loop will execute indefinitely (infinite loop) causing a stack overflow - I'm assuming that's what you mean by "breaks the browser". This is because your condition is always true:startTime and currentTime are the same value (currentTime - startTime < 200)
Try this instead:
while(currentTime - startTime < ms) {
time = new Date();
currentTime = time.getTime();
}
Creating a new Date object and calling time.getTime() inside the loop will return the latest time and should fix your problem. Use getTime() instead of getMilliseconds() because the latter only returns a number between 0 and 999 (ie. less than a second). This limited upper range will be problematic for your code because getMilliseconds() will only return the number of milliseconds elapsed since the previous second.
You can you generator as lazy evaluating. Please see below example. To run an infinite loop setInterval. You can modify the code according to your use.
This is supported on es6 supported browser and node 8.9.1LTS or above.
function* asyncRandomNumbers() {
let tm = new Date().getTime();
while (true) {
let updatedTm = new Date().getTime()
if(updatedTm - tm >= 1000){
tm = updatedTm;
yield tm;
}
}
}
for (var val of asyncRandomNumbers()) {
console.log(val) // outputs 0 — 9
}

Cannot print message according to time

I've three different times, two of them are in string forms (time1 and time2) and one from system date currDate. Next step according to the one of two above times I want to print messages when the system date reaches one of them. For this I've function callEachMinute that calls each minute to get system time (but here in code I did not include the whole procedure). Here is the current status of the code:
Script:
function callEachMinute() {
var currDate = new Date();
var time_1 = '8:30';
var time_2 = '23:00';
timeComparison(currDate, time_1, time_2)
}
function timeComparison(currTime, time1, time2) {
// Time 1 formatting
var t1 = new Date();
var parts1 = time1.split(":");
t1.setHours(parts1[0],parts1[1]);
// Iftor-Time formatting
var t2 = new Date();
var parts2 = timeI.split(":");
t2.setHours(parts2[0],parts2[1]);
/* Notification procedure */
if (currTime == t1) {
// Message for Time1
alert("Time 1 is reached");
}
if (currTime == t2) {
// Message for Time2
alert("Time 2 is reached");
}
}
Problem:
When the system time is reached one of times (time1 or time2) nothing happens. Any solution for this problem?
There are a few things that could be problematic here.
You set up a Date object then want to compare it to currTime:
if (currTime == t1) {
unfortunatley Javascript's == operator when applied to objects compares two objects to see if they are references to the same object, so even if currTime and t1 contained exactly the same time this check would evaluate to false since they are different instances. You could do this by converting to a string:
if (currTime.toString() == t1.toString) {
which would work if the string representations for each data work out the same.
However, a more straight forward approach might be to tackle this the other way around - extract the hours and minutes from currTime, build a string and compare that to your time strings. Something like:
// in timecomparison function
var hrs = currTime.getHours();
var mins = currTime.getMinutes();
var now = hrs+":"+mins
// now do comparisons
if (now == time1 ) {
....
}
and so on.

Detecting changes to system time in JavaScript

How can I write a script to detect when a user changes their system time in JS?
There is no (portable) way to track a variable in JavaScript. Also, date information does not lie in the DOM, so you don't get the possibility of a DOM event being triggered.
The best you can do is to use setInterval to check periodically (every second?). Example:
function timeChanged(delta) {
// Whatever
}
setInterval(function timeChecker() {
var oldTime = timeChecker.oldTime || new Date(),
newTime = new Date(),
timeDiff = newTime - oldTime;
timeChecker.oldTime = newTime;
if (Math.abs(timeDiff) >= 5000) { // Five second leniency
timeChanged(timeDiff);
}
}, 500);
Check in an interval function that the time has not changed too much:
function getTime() {
var d = new Date();
return d.getTime();
}
function checkTime() {
if (Math.abs(getTime() - oldtime) > 2000) { // Changed by more than 2 seconds?
alert("You changed the time!");
}
oldtime = getTime();
}
var oldtime = getTime();
setInterval(checkTime, 1000); // Check every second that the time is not off
Tested on Windows with Opera & FF and works flawlessly.
Don't think there is a solution to what you are asking for but you can get the users timezone offset.
new Date().getTimezoneOffset() * -1
This returns the offset in minutes from GMT. Bare in mind though this does not take DST into consideration.
var last_time = new Date().getTime();
setInterval(function() {
var time = new Date().getTime();
var offset = time - last_time;
if(offset < 0 || offset > 1500) {
// Time has been changed
}
last_time = time;
}, 1000);
In theory, this should work. It will check every second to make sure the time hasn't been changed. Note that I use 1100 milliseconds as most JS interpreters don't fire off events at exactly the time specified.
Hope this helps!
use performance.now() to get duration, which will be independent of system clock
see https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
And then you can compare performance.now() elapsed with Date.now() elapsed to see whether they are diff too much.
Do you mean if they are changing their own system time to something that is wrong? You can ask the user for their time zone and get the correct time from the server, and then compare it to the user's system time.
You could check every 30 seconds, etc. If the new Time is off by more than 30 seconds +/- some threshold, you could do a more exhaustive comparison to determine how much it has been changed.

Categories

Resources