1

i need to show current time in html code, but the javascript code only work once?

 $(document).ready(function () {
     function updateClock(ele){
         var current_time = new Date();
         var current_time_str = current_time.toLocaleTimeString();
         ele.text(current_time_str);
         console.log(current_time_str);
     }

   setInterval(updateClock($('#clock')) , 1000 );
 })

It's work different some others languages like C,Object-C or Python, it's so misleading for me.

Phil
  • 157,677
  • 23
  • 242
  • 245
jett chen
  • 1,067
  • 16
  • 33
  • 1
    Related: [How can I pass a parameter to a setTimeout() callback?](https://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback) – Jonathan Lonowski May 28 '18 at 06:57

2 Answers2

3

You need to wrap the calling part in a function, because it is called only once and returns undefined as calling value.

setInterval(() => updateClock($('#clock')), 1000);

Another possibillity is to use the third and following arguments of setInterval

setInterval(updateClock, 1000, $('#clock'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Put the updateClock inside setInterval callback function

$(document).ready(function() {
  function updateClock(ele) {
    var current_time = new Date();
    var current_time_str = current_time.toLocaleTimeString();
    ele.text(current_time_str);
  }

  setInterval(function() {
    updateClock($('#clock'))
  }, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clock"></div>
brk
  • 48,835
  • 10
  • 56
  • 78