Click here to Skip to main content
15,891,708 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have a javascript in which I would have 2 date object defined as new Date(). In the middle of the javascript, I would have some logic processing the 2 date object and modify their value accordingly. Finally, I would have a simple subtraction to retrieve the difference the 2 date object.
My codes as follow:
var dateObj = new Date();
var dateObjNew = new Date();

var i = 0;
while(i < 1){
//some logic
anything.then(function(data){
  dateObj.setTime(dateObj.getTime() + 300000); //300000 is in milliseconds
  //means I would add 300k milliseconds into the Date object
});

anything2.then(function(data){
  dateObjNew.setTime(dateObjNew.getTime() + 100000); //add 100000 milliseconds here
});
alert('Remaining Time: '+ (dateObj - dateObjNew)); //here the alert will show 'Remaining Time: 0' because the 2 date objects value has been defaulted back to new Date() where they do not take the latest modified values.
i++;
}


What I have tried:

1. Tried to add getTime() in the final alert but results still is 0.
2. Search online but articles browsed seems not to have this kind of issue.
3. Tried add alert within the 2 .then(function(data)) and the date objects have been updated with the intended milliseconds. E.g. DateTime now been added 300000 milliseconds.
Posted
Updated 15-Oct-18 22:37pm
v2
Comments
F-ES Sitecore 16-Oct-18 4:40am    
The code in your "then" statements isn't running immediately, it is asynchronous so the while loop continues to process at the same time and it runs the alert before the date objects have been updated.
Richard MacCutchan 16-Oct-18 4:46am    
redacted
Kornfeld Eliyahu Peter 16-Oct-18 13:50pm    
I assume that 'anything' and 'anything2' supposed to be promises, but where they are?
Jamie888 16-Oct-18 22:51pm    
hello gentlemen, thanks for providing the explanation above. They give me a good hint and more understanding on the .then nature. I have modified my script by adding another .then after the function end part and wrapped the alert into the new .then. I am able to get the updated date objects now.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900