javascript - JAVASCRIPT - 如何每秒更新变量
问题描述
我需要将开始时间与当前时间进行比较,但我不知道如何使当前时间始终刷新到我比较的变量。我为编辑道歉,在以前的解决方案中我错误地描述了错误
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!');
}
谢谢您的帮助
解决方案
您只需要调用一次间隔,因为actualTime
它在函数内部。为了更清楚地看到它,如果您删除变量并记录new Date()
:
function logActualTime() {
console.log('Now is:', new Date());
}
setInterval(logActualTime, 1000);
推荐阅读
- javascript - 如何将对象数据推送到数组中
- c++ - 在 Windows 中枚举音频会话
- r - 如何在 R 中使用 igraph 制作交互式网络图
- swift - 如何使用 SwiftUI 从文本中提取 Hashtags?
- ios - 如何允许用户在页面的任何位置添加文本?(迅速)
- macos - macOS 终端(或 AppleScript) - 从 Dock 中删除文件夹
- php - 加入收件箱和发件箱表
- python - Python 条件 if 语句
- java - 使用 CompletableFuture.runAsync() 与 ForkJoinPool.execute()
- python - 使用 Python 提高比较分析的速度