setInterval()不起作用

setInterval() not working

本文关键字:不起作用 setInterval      更新时间:2023-09-26

我试图在"1秒"的setInterval()运行一个函数,但这有点问题。我已经做了这里所示的一切,但它不工作。

下面是我的代码:
<script>
   function test(db_time)
   {
      var c_db_time= db_time/1000; 
      var current_time = new Date().getTime()/1000;
      return Math.round(current_time - c_db_time);
   }
   $(".elapsed_time").each(function() {
      var time_r = $(this).data('time_raw');
      var inter = $(this).html(time_ago(time_r));//parameter to function
      setInterval(inter,1000)
   });
</script>

Uncaught SyntaxError: Unexpected identifier


解决方案找到感谢@Bommox &@Satpal

 $(".elapsed_time").each(function() {
var time_r = $(this).data('time_raw');
    var self = $(this);
    var inter = function() {self.html(time_ago(time_r));}
    setInterval(inter, 1000);
  });

setInterval函数的第一个参数中,你应该传递一个函数或一个匿名函数,如

setInterval(function(){
    console.log("1s delayed")
},1000);

如前所述,第一个参数应该是函数:

 var self = $(this);
 var inter = function() {
     self.html(time_ago(time_r));
 }
 setInterval(inter, 1000);
var self = this;
setInterval(function(){
     $(self).html(time_ago(time_r));
},1000);

看这里:window.setInterval

window.setTimeout( function() { /*your code which you want to execute after fixed interval, it can function name or lines of code*/}, /*fixedInterval*/);
window.setTimeout( function() { alert("Hello World!"); }, 5000); // it will execute after 5 seconds