I have two asp.net buttons and i want to calculate the time difference in between the clicks of the buttons using JS
Button 1 - Start
Button 2 - Next
First I got the current time on the click of the "start" button in getStartTime() function. and similarly for the second button in getEndTime() function.
For calculating the time difference I use another function calculateDifference() and call the above functions. I want to calculate the difference after the "Next" button click. The problem is getStartTime() is calculating the current time every time. How can
I store the time of button click in a variable and return it to another function?
var startTime, startHour, startMin, startSec, endTime, endHour, endMin, endSec, diffTime, stTime, etTime;
//To Get the click time of Start Button(btnStart_OnClick)
function getStartTime() {
startTime = new Date();
startHour = startTime.getHours();
startMin = startTime.getMinutes();
startSec = startTime.getSeconds();
if (startHour > 0) {
startHour = startHour * 3600;
}
if (startMin > 0) {
startMin = startMin * 60;
}
stTime = startHour + startMin + startSec;
return stTime;
}
//To get the click time of Next Button
function getEndTime() {
endTime = new Date();
endHour = endTime.getHours();
endMin = endTime.getMinutes();
endSec = endTime.getSeconds();
if (endHour > 0) {
endHour = endHour * 3600;
}
if (endMin > 0) {
endMin = endMin * 60;
}
etTime = endHour + endMin + endSec;
return etTime;
}
function calculateDifference() {
var start = getStartTime(); // On calling this function, current date is returned instead of the click time of 'Start' button
var end = getEndTime();
var diff = end - start;
return diff;
}
//Button Next_OnClick
function newTimeLeft() {
var difference = calculateDifference();
var newTimeLeft = 1800 - difference;
if (newTimeLeft > 0) {
javascript_countdown.init(newTimeLeft, 'javascript_countdown_time');
}
}
If you need time differences between two button clicks you better keep track of the two timestamps. Then differentiate between two I guess this should work -
let startTime, endTime;
function getStartTime() {
startTime = new Date().getTime()
}
function getEndTime() {
endTime = new Date().getTime()
}
function calculateDifference() {
return startTime - endTime;
}
Calling calculateDifference() will return the time difference in milliseconds. Rest is up to you.
Hope this helps.