I do testing. The time for passing the test I get from the database in seconds. There is a problem with the timer. Countdown goes. Everything is working. But how to make it so that when the page is constantly updated, it does not stand still? Thank you in advance.

function showTimer(date_t) { var date = new Date(); date = date.getTime(); var timer = date_t - date; if (date_t > date) { var h = parseInt(timer / (60 * 60 * 1000)) % 24; if (h < 10) { h = '0' + h; } //Приводим результат к строке var i = parseInt(timer / (1000 * 60)) % 60; //если полученное число меньше 10 прибавляем 0 if (i < 10) { i = '0' + i; } //Приводим результат к строке var s = parseInt(timer / 1000) % 60; //если полученное число меньше 10 прибавляем 0 if (s < 10) { s = '0' + s; } $("#timer").html(h + ":" + i + ":" + s); function secOut() { if (s == '00') { if (i == '00') { if (h == '00') { alert("Время вышло"); } else { h--; i = '59'; s = '59'; if (h < 10) { h = '0' + h; } } } else { i--; s = '59'; if (i < 10) { i = '0' + i; } } } else { s--; if (s < 10) { s = '0' + s; } } $("#timer").html(h + ":" + i + ":" + s); localStorage["time"]=$("#timer").text(); } setInterval(secOut, 1000); } else { alert("Время вышло"); } 

}

 $(function () { $(document).ready(function () { var arr = window.location.href.split('/'); var test_id = arr[5]; if(localStorage.getItem("time")) { var arr=localStorage.getItem("time").split(':'); arr[0]*=1; arr[1]*=1; arr[2]*=1; var time=(arr[0]*3600+arr[1]*60+arr[2])*1000; var date_t = new Date(); date_t = date_t.getTime() + time; showTimer(date_t); } else { $.ajax({ type: 'POST', url: "/test/get_test_time", data: {id: test_id}, dataType: 'text', success: function (data) { var data1 = data * 1000; var date_t = new Date(); date_t = date_t.getTime() + data1; showTimer(date_t); } }); } }); 

});

  • save time in local storage and read back after refreshing the page. - Fess Laeda
  • I write @IlonMask to localStorage. It does not help if you update faster than a second - Kairat

0