我需要比较开始时间和当前时间,但是我不知道如何使当前时间始终刷新到我比较的变量。 我为此编辑表示歉意,在先前的解决方案中,我错误地描述了该错误
var timeout = $payuEle.attr("data-ajax-timeout");
// VERIFICATION OF TIMEOUT TIME //
//////////////////////////////////
// Creates a new start date
var startTime = new Date();
// Converts the start date to milliseconds
var startTimeInMilliseconds = startTime.getTime();
// Converts seconds from the 'timeout' attribute to milliseconds
var secondsInMilliseconds = timeout * 1000;
// Adds milliseconds of start date + 'timeout' = time when authentication expires
var endTimeInMilliseconds = startTimeInMilliseconds + secondsInMilliseconds;
// Converts milliseconds of end time to date (functionally not redeemed, only for testing purposes in console)
var endTime = new Date(endTimeInMilliseconds);
// Predefined variable, which then saves the current time
var readyForActualTime = "";
// A variable calling a function for the current time
var actualTimeStore = getActualTime(readyForActualTime);
var actualTimeStoreInMilliseconds = actualTimeStore.getTime();
// Rounds the last two milliseconds to avoid minor variations
var endTimeCompare = Math.round(endTimeInMilliseconds/100)*100;
var startTimeCompare = Math.round(actualTimeStoreInMilliseconds/100)*100;
console.log(startTime, endTime);
// A function that creates the current time
function getActualTime(ocekavanyParametr) {
// Creates the current time
var actualTime = new Date();
// Returns current time to variable ''
return actualTime;
}
// It restores function every second to keep the actual time
setInterval(getActualTime, 1000);
// Compare times
if (endTimeCompare === startTimeCompare) {
alert('Its a match!');
}
谢谢您的帮助
答案 0 :(得分:0)
您仅需要调用一次间隔,因为actualTime
在函数内部。为了更清楚地看到它,如果您删除变量并登录new Date()
:
function logActualTime() {
console.log('Now is:', new Date());
}
setInterval(logActualTime, 1000);
答案 1 :(得分:0)
您可能想要这个。您过于复杂了,需要在循环内创建时间
var timeout = 5; // seconds
// VERIFICATION OF TIMEOUT TIME //
//////////////////////////////////
// Creates a new start date
var startTime = new Date();
startTime.setMilliseconds(0); // normalise
// Converts the start date to milliseconds
var startTimeInMilliseconds = startTime.getTime();
// Converts seconds from the 'timeout' attribute to milliseconds
var secondsInMilliseconds = timeout * 1000;
// Adds milliseconds of start date + 'timeout' = time when authentication expires
var endTimeInMilliseconds = startTimeInMilliseconds + secondsInMilliseconds;
// It restores function every second to keep the actual time
var tId = setInterval(getActualTime, 1000);
// A function that creates the current time
function getActualTime() {
// Creates the current time
var actualTime = new Date();
actualTime.setMilliseconds(0); // normalise
actualTimeInMilliseconds = actualTime.getTime();
console.log(new Date(endTimeInMilliseconds),new Date(actualTimeInMilliseconds));
// Compare times
if (endTimeInMilliseconds === actualTimeInMilliseconds) {
clearTimeout(tId)
console.log('Its a match!');
}
}