首页 > 解决方案 > 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!');
        }

谢谢您的帮助

标签: javascriptsetinterval

解决方案


您只需要调用一次间隔,因为actualTime它在函数内部。为了更清楚地看到它,如果您删除变量并记录new Date()

function logActualTime() {
  console.log('Now is:', new Date());
}
 
setInterval(logActualTime, 1000);


推荐阅读