JAVASCRIPT - Как обновлять переменную каждую секунду - PullRequest
1 голос
/ 02 октября 2019

Мне нужно сравнить время начала с текущим временем, но я не знаю, как заставить текущее время всегда обновляться к моей переменной, которую я сравниваю. Прошу прощения за правку, в предыдущем решении я ошибочно описал ошибку

        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!');
        }

Спасибо за помощь

Ответы [ 2 ]

0 голосов
/ 02 октября 2019

Вы, вероятно, хотите этого. Вы чрезмерно усложняете вещи, и вам нужно создать времена внутри цикла

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!');
  }
}
0 голосов
/ 02 октября 2019

Вам нужно вызывать интервал только один раз, потому что actualTime находится внутри функции. Чтобы увидеть это более четко, если вы удалите переменную и войдите new Date():

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