views:

119

answers:

7

I want to create a jQuery iterative timer. For this I wrote the following script:

$(document).ready(function(){
    var t;
    function x()
    {
        alert('x')
        t = setTimeout("x()",1000);
    }
    x();
});

First time the function x() called successfully. But from the next function x() is detect as undefined. What could I do?

A: 

How about using setInterval instead?

W3Schools page

Josh Stodola
+3  A: 

This is because you define x() in closure. Define x as global function. Or pass it as function, instead of string:

function x() {

};

setTimeout(x, 1000);
Anatoliy
What about `arguments.callee`?
Josh Stodola
A: 

function x() is only visible inside the anonymous function. Try putting function x() outside the callback for the onload event. That is,

function x()
{
  alert('x')
  t = setTimeout("x()",1000);
}

$(document).ready(function(){
    var t;
    x();
});
devpl
A: 

you can do:

$(document).ready(function(){
 window.setTimeout("updateTime()", 1000);   
});


function updateTime() {
 var now = new Date();
 $('#box span.start:not(:empty)').each(
  function(s) {
   var start = $('#box').children('span.start').html();
    $('box').children('span.time').html(formatMillis(now.getTime() - start));
  }
 );
 window.setTimeout("updateTime()", 1000);
}
JorgeO
A: 

I like the jQuery Timers plugin

CmdrTallen
A: 

Hey guys,

Read your latest comments and I tried to integrate Jorge's updatetime() (html object id) box combo (Oct 8 at 19:22). It is clean, I like it. In my integration, updatetime() get called every second but the code inside function(s) never gets executed.

Could it be because my html object is not valid? It is in the body and defined as <div id="box"><p>time</p></div>.

Stephane

P.S.: My version of Jorge's updatetime function is

function updateTime() 
{
        var now = new Date();
        $('#box span.start:not(:empty)').each(
                function(s) 
  {
                        var start = $('#box').children('span.start').html();
                         $('box').children('span.time').html(formatMillis(now.getTime() - start));
                }
        );
        window.setTimeout("updateTime()", 1000);
}
Stephane
A: 

Two things:

  1. Don't use a string in setTimeout

    setTimeout(x, 1000);
    

    or

    setTimeout(function(){ x(); }, 1000);
    
  2. SetInterval is your friend in these situations

    setInterval(x, 1000);
    

Note that the function you pass to setTimeout or setInterval will be passed lateness (the number of milliseconds late the timer actually fired) as the first argument. This won't affect you just yet (since x doesn't take any arguments), but may bite you later on. This won't be the case if you use an anonymous function (second example), since it'll receive the lateness argument.

Sidnicious