2017-12-16 12 views
-2

실시간 시계를 만들려고했지만 문제가 있습니다. setTimeout은 실제로 시계가 작동하지 않고 시계 자체가 업데이트되지 않습니다. 도와 드릴까요? 그러나 당신이 그것을 그렇게 결코 업데이트, 함수의 currentDate 외부의 인스턴스를,이 Javascript 실시간 시계에서 setTimeout을 어떻게 사용해야합니까?

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <title></title> 
 
</head> 
 

 
<body> 
 
    <p id="p"></p> 
 
    <script> 
 
    var currentDate = new Date(); 
 

 
    function startClock() { 
 

 
     time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); 
 

 
     document.getElementById("p").innerHTML = time; 
 

 
     setTimeout(startClock, 1000); 
 
    } 
 

 
    startClock(); 
 
    </script> 
 
</body> 
 

 
</html>

답변

1

사실, setTimeout이 잘 작동 :

내가 쓴 코드입니다.

날짜가 인스턴스화 될 때만 캡처되기 때문에 이는 업데이트되지 않습니다. 즉, 인스턴스를 한 번만 인스턴스화하면 인스턴스화 된 시점부터 만 유지됩니다.

이 시도 : 나는 기능에하는 currentDate 좀 넣어해야하는 이유

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <title></title> 
 
</head> 
 

 
<body> 
 
    <p id="p"></p> 
 
    <script> 
 
    
 

 
    function startClock() { 
 
     var currentDate = new Date(); 
 
    
 
     time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); 
 

 

 
     document.getElementById("p").innerHTML = time; 
 

 
     setTimeout(startClock, 1000); 
 
    } 
 

 
    startClock(); 
 
    </script> 
 
</body> 
 

 
</html>

+0

당신이 또한 설명 할 수 있을까? – Pier

+0

probs, 나는 그것을 추가했습니다. 그걸 정리 해줄 수 있니? – user184994