2

I am trying to run a function at setInterval() of "1 second", but it is a bit problematic. I have done everything as shown here but it doesn't work.

Here is my code :

<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>

And the error is :Uncaught SyntaxError: Unexpected identifier


Solution found thanks to @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);
  });
Dev Man
  • 2,114
  • 3
  • 23
  • 38

4 Answers4

7

into setInterval function's first parameter you should pass a function or an anonymous function like

setInterval(function(){
    console.log("1s delayed")
},1000);
R3tep
  • 12,512
  • 10
  • 48
  • 75
Roland Kákonyi
  • 583
  • 4
  • 12
  • ok but now i get a new error `Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined ` – Dev Man May 06 '14 at 13:19
5

As said before, first argument should be the function:

 var self = $(this);
 var inter = function() {
     self.html(time_ago(time_r));
 }
 setInterval(inter, 1000);
Satpal
  • 132,252
  • 13
  • 159
  • 168
Jorgeblom
  • 3,330
  • 1
  • 23
  • 24
  • 6
    I don't think this will work how you expect it to. When the function is run, won't `this` refer to the window? – JoseM May 06 '14 at 13:17
  • I'm not sure because you define function out of the setInterval. But now it's better, thanks! – Jorgeblom May 06 '14 at 13:18
  • @Bommox, I have edited your answer. If you feel my edit is incorrect Please feel free to rollback – Satpal May 06 '14 at 13:19
  • 2
    It doesn't matter where you define the function, the variable `this` will always refer to calling function context (and can be changed by the caller) – JoseM May 06 '14 at 13:20
  • The other thing you have to take into account is that the `time_r` variable might need to be re-read depending on how it is used – JoseM May 06 '14 at 13:22
0
var self = this;
setInterval(function(){
     $(self).html(time_ago(time_r));
},1000);
Roland Kákonyi
  • 583
  • 4
  • 12
ekans
  • 1,662
  • 14
  • 25
0

Have a look here : 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
SK.
  • 4,174
  • 4
  • 30
  • 48