2016-06-25 17 views
0

setInterval()を使用するタイマーを設定しようとしています.1000ミリ秒ごとに変数が1ずつ増えます。 idを持つ簡単な段落を設定し、innerHTMLを変数timerに変更します。これは1,2,3までカウントされますが、コードが実行されるたびに段落にNaNが表示されます。誰も助けることができますか?ここで段落のinnerHTMLをNaNを返す変数に変更する

コードです:

<!DOCTYPE html> 
<html> 
<body onload=autoTrafficLight()> 

<p id="msg">0</p> 

<table border="10px" style="background-color: rgb(0, 0, 0);"> 
<tr> 
<td width="30px" height="30px" style="background-color: rgb(0, 0, 0);" id="1"></td> 
</tr> 
<tr> 
<td width="30px" height="30px" style="background-color: rgb(0, 0, 0);" id="2"></td> 
</tr> 
<tr> 
<td width="30px" height="30px" style="background-color: rgb(0, 0, 0);" id="3"></td> 
</tr> 
</table> 

<script> 
var timer = 0 
function autoTrafficLight() { 
    setInterval(function() { 
     var timer = timer + 1;  
     document.getElementById("msg").innerHTML = +timer 
    }, 1000) 

} 
</script> 
</body> 
</html> 
+0

私はsetIntervalの内容を 'timer + = 1; document.getElementById( "msg")。innerHTML = timer; '。ああ、あなたはセミコロンを省略することを決定しましたか? – gcampbell

答えて

1

あなたはタイマ変数を再宣言しているので、基本的にあなたが一緒に未定義と1を追加しようとしていました。タイマ=タイマ+ 1;修正するか、タイマ++を使用します。

var timer = 0 
function autoTrafficLight() { 
    setInterval(function() { 
     timer = timer + 1;  
     document.getElementById("msg").innerHTML = timer 
    }, 1000) 

} 
1

JSフィドルリンク:JS Fiddle

グローバル変数としてタイマーを定義します。

var timer = 0 
function autoTrafficLight() { 
    setInterval(function() { 
     timer = timer + 1; 
     console.log(timer); 
     document.getElementById("msg").innerHTML = timer; 
    }, 1000) 

} 
関連する問題