1

I am using setInterval in Javascript. For a simple example I tried to update a time displayed.

var tim = new Date();
function loadLog(){
    document.getElementById('timebox').innerHTML=tim.getTime();
}
window.setInterval(loadLog, 1000);

But the time is not updated. Why? How can I update the variable inside setInterval?

Thanks

user2212461
  • 3,105
  • 8
  • 49
  • 87

1 Answers1

3

Generate a new date each time instead of always showing the same one :

function loadLog(){
    var tim = new Date();
    document.getElementById('timebox').innerHTML=tim.getTime();
}
window.setInterval(loadLog, 1000);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Great, works with the time. When I am using jQuery, why doesn't this update as well? `function loadLog(){ var test; $.get('get_feedback.php', function(data) { test=data; }); document.getElementById('chatbox').innerHTML=test; } window.setInterval(loadLog, 2500); – user2212461 Sep 04 '13 at 14:55
  • Because $.get is asynchronous. Use `function loadLog(){var test; $.get('get_feedback.php', function(data) { test=data;document.getElementById('chatbox').innerHTML=test; }); }window.setInterval(loadLog, 2500);` – Denys Séguret Sep 04 '13 at 14:57
  • See this related question : http://stackoverflow.com/questions/12475269/variable-doesnt-get-returned-from-ajax-function – Denys Séguret Sep 04 '13 at 14:58
  • But using setInterval for that is wrong : if your network or server is slow, your page will explode. Use setTimeout (if needed ask another question, it's unrelated and painful to code in comments). – Denys Séguret Sep 04 '13 at 14:59
  • But the variable "data" is not updated (the return from the get_feedback.php changes). Is that not possible because it is async? – user2212461 Sep 04 '13 at 15:02
  • I don't understand your comment but the answer is probably in the link I gave, did you understand it ? – Denys Séguret Sep 04 '13 at 15:04
  • I didn't so I asked a new question: http://stackoverflow.com/questions/18618183/updating-html-code-with-javascript-when-php-return-changed – user2212461 Sep 04 '13 at 15:41