2017-09-18 1 views
0

시험 웹 응용 프로그램을 개발 중이며 JavaScript를 사용하여 카운트 다운을 수행하고 쿠키에 시간을 저장하므로 페이지가 열릴 때 새로 고침 또는 의도적으로 닫은 경우 처음부터 카운트 다운을 반복해서 다시 시작하지 않습니다.JavaScript를 사용하여 페이지를 새로 고치거나 닫은 후 타이머를 다시 시작하지 않고 쿠키에 카운트 다운 타이머 저장

내 관찰에 따르면 쿠키를 저장하고 마지막 타이밍부터 검색 한 다음 바로 처음부터 다시 시작합니다.

<script> 
var loginUser = "<?php echo $uid ?>"; 
// Defining the set Cookie method 
function setCookie(cname,cvalue,exdays) { 
    var d = new Date(); 
    d.setTime(d.getTime() + (exdays*24*60*60*1000)); 
    var expires = "expires=" + d.toGMTString(); 
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; 
} 
// Defining get cookie function 
function getCookie(cname) { 
    var name = cname + "="; 
    var decodedCookie = decodeURIComponent(document.cookie); 
    var ca = decodedCookie.split(';'); 
    for(var i = 0; i < ca.length; i++) { 
     var c = ca[i]; 
     while (c.charAt(0) == ' ') { 
      c = c.substring(1); 
     } 
     if (c.indexOf(name) == 0) { 
      return c.substring(name.length, c.length); 
     } 
    } 
    return ""; 
} 

// Return or Get the time stored in the cookie if available 
    var oldTime = parseInt(getCookie(loginUser), 10); 

// Set the date we're counting down to 
var countDownDate = new Date().getTime() + ((4/180)*60*60*1000); 

// Update the count down every 1 second 
var x = setInterval(function() { 

    // Get todays date and time 
    var now = new Date().getTime(); 
    // 
    var distance = countDownDate - now; 
    var oldTime = parseInt(getCookie(loginUser), 10); 
     setCookie(loginUser, distance, 30); 

    if(isNaN(oldTime)) 
    { 
     alert("new user NaN"); 
     // Find the distance between now an the count down date 

     // Time calculations for days, hours, minutes and seconds 
     var days = Math.floor(distance/(1000 * 60 * 60 * 24)); 
     var hours = Math.floor((distance % (1000 * 60 * 60 * 24))/(1000 * 60 * 60)); 
     var minutes = Math.floor((distance % (1000 * 60 * 60))/(1000 * 60)); 
     var seconds = Math.floor((distance % (1000 * 60))/1000); 
    } 
    else{ 


     // Time calculations for days, hours, minutes and seconds from the saved distance 
     // in the cookie 
     var days = Math.floor(oldTime/(1000 * 60 * 60 * 24)); 
     var hours = Math.floor((oldTime % (1000 * 60 * 60 * 24))/(1000 * 60 * 60)); 
     var minutes = Math.floor((oldTime % (1000 * 60 * 60))/(1000 * 60)); 
     var seconds = Math.floor((oldTime % (1000 * 60))/1000); 
    } 





    //Output the result in an element with id="timer" 
    document.getElementById("timer").value = hours + "h " + minutes + "m " + seconds + "s "; 
    //var n = oldTime.toString(); 
    //document.getElementById("timer").value = n; 


    // If the count down remains 15 minutes, write some text 

if (minutes == 1 && seconds == 1) { 
     alert("Hello! 1 minute gone"); 
    } 


    // If the count down is over, write some text 
    if (distance < 0) { 
     clearInterval(x); 
     document.getElementById("timer"); 
     timer.value= "EXPIRED"; 
     alert("Hello! Exam is over"); 
     location = "http://localhost:81/aquaexam/exam_complete.php?id=1"; 
    } 
}, 1000); 
</script> 

아래

내 자바 스크립트 코드 내 HTML 코드

<tr width="100%" style="text-align:right; align:right;"> <td > <input type="text" name="timer" id="timer" size="20" readonly="true" style="text-align:center;"/></td></tr> 
+0

왜 로컬 스토리지를 사용하지 않는? – Thusitha

+0

그래,하지만 전에 로컬 스토리지 기술을 사용하지 않았어. 나는 그것을 바로 공부하고있다. 나는 또한 set-cookie 메서드의 호출 시점에서 만료를 지정하지 않았기 때문에 문제가 있다고 생각합니다. – Edwinfad

+0

그냥 쉽습니다. localstorage.setItem ("counter", 1000); var counter = localstorage.getItem ("counter"); – Thusitha

답변

0

나는 마침내 그것을 해결했다.

최종 JavaScript 코드.복사하여 붙여 넣기 만하면됩니다.

<script> 
// define variable for cookie name using the user login id 
var loginUser = "<?php echo $uid ?>"; 
// Defining the set Cookie method 
function setCookie(cname,cvalue,exdays) { 
    var d = new Date(); 
    d.setTime(d.getTime() + (exdays*24*60*60*1000)); 
    var expires = "expires=" + d.toGMTString(); 
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; 
} 
// Defining get cookie function 
function getCookie(cname) { 
    var name = cname + "="; 
    var decodedCookie = decodeURIComponent(document.cookie); 
    var ca = decodedCookie.split(';'); 
    for(var i = 0; i < ca.length; i++) { 
     var c = ca[i]; 
     while (c.charAt(0) == ' ') { 
      c = c.substring(1); 
     } 
     if (c.indexOf(name) == 0) { 
      return c.substring(name.length, c.length); 
     } 
    } 
    return ""; 
} 

// Function that will call when document loaded. 
window.onload = function() { 
// Return or Get the time stored in the cookie if available 
    var oldTime = parseInt(getCookie(loginUser), 10); 

    if(isNaN(oldTime) == false) 
    { 
      // Reset the date or time we're counting down to by 
      //adding the Cookie time to the present for continous countdown 
      var countDownDate = new Date().getTime() + oldTime; 

     // Update the count down every 1 second  
     var x = setInterval(function() { 
     // Get todays date and time 
     var now = new Date().getTime(); 
      // Find the distance between now an the count down date 
     var distance = countDownDate - now; 
     setCookie(loginUser, distance, 30); 
     // Update the count down every 1 second 

     // Time calculations for days, hours, minutes and seconds from the saved distance 
     // in the cookie 
     var days = Math.floor(distance/(1000 * 60 * 60 * 24)); 
     var hours = Math.floor((distance % (1000 * 60 * 60 * 24))/(1000 * 60 * 60)); 
     var minutes = Math.floor((distance % (1000 * 60 * 60))/(1000 * 60)); 
     var seconds = Math.floor((distance % (1000 * 60))/1000); 


     //Output the result in an element with id="timer" 
    document.getElementById("timer").value = hours + "h " + minutes + "m " + seconds + "s "; 

      // If the count down remains 15 minutes, notification alert 
    if (minutes == 15 && seconds == 1) { 
     alert("Hello! 15 minutes to go"); 
    } 

    // If the count down remains 5 minutes, notification alert 
    if (minutes == 5 && seconds == 1) { 
     alert("Hello! 5 minutes to go"); 
    } 

// If the count down is over, notification alert and automatically submits the exam 
    if (distance < 0) { 
     clearInterval(x); 
     document.getElementById("timer"); 
     timer.value= "EXPIRED"; 
     alert("Hello! Exam is over"); 
     location = "http://localhost:81/aquaexam/exam_complete.php?id=1"; 
    } 

     }, 1000); 
    } 
    else{ 

    // Set the date or time we're counting down to 
    var countDownDate = new Date().getTime() + ((1)*60*60*1000); 

      // Update the count down every 1 second 
       var x = setInterval(function() { 
      // Get todays date and time 
       var now = new Date().getTime(); 
      // Find the distance between now an the count down date 
       var distance = countDownDate - now; 

       setCookie(loginUser, distance, 30); 


     // Find the distance between now an the count down date 

     // Time calculations for days, hours, minutes and seconds 
     var days = Math.floor(distance/(1000 * 60 * 60 * 24)); 
     var hours = Math.floor((distance % (1000 * 60 * 60 * 24))/(1000 * 60 * 60)); 
     var minutes = Math.floor((distance % (1000 * 60 * 60))/(1000 * 60)); 
     var seconds = Math.floor((distance % (1000 * 60))/1000); 

    //Output the result in an element with id="timer" 
    document.getElementById("timer").value = hours + "h " + minutes + "m " + seconds + "s "; 


     // If the count down remains 15 minutes, notification alert 
    if (minutes == 15 && seconds == 1) { 
     alert("Hello! 15 minutes to go"); 
    } 

    // If the count down remains 5 minutes, notification alert 
    if (minutes == 5 && seconds == 1) { 
     alert("Hello! 5 minutes to go"); 
    } 

// If the count down is over, notification alert and automatically submits the exam 
    if (distance < 0) { 
     clearInterval(x); 
     document.getElementById("timer"); 
     timer.value= "EXPIRED"; 
     alert("Hello! Exam is over"); 
     location = "http://localhost:81/aquaexam/exam_complete.php?id=1"; 
    } 
}, 1000); 
    } 
} 

내 HTML 코드

<tr width="100%" style="text-align:right; align:right;"> <td > <input type="text" name="timer" id="timer" size="20" readonly="true" style="text-align:center;"/></td></tr> 
관련 문제