views:

59

answers:

3

Hi there!
I guess I need help on this one.
I'm not new to Javascript but then I realize I don't know how to use setTimeout().

I have tried this:

$(document).ready(function(){

  setTimeout('changeit()',1000); // I have also tried setTimeout('changeit',1000);
  // var t = setTimeout('changeit()',1000); <--- tried also something like this.

  // changeit(); <-- works when i do this.

  function changeit(){
    $('#hello').html('Hello World - this was inserted using jQuery');
    // #hello is <p id="hello">Hello World</p>
  }
})

Can anyone help me with this one.
Please make me realize something.
Thanks.

+3  A: 

Pass a reference to the changeit function instead of a string of JavaScript code.

$(document).ready(function() {
    setTimeout(changeit, 1000);
    function changeit() {
        $("#hello").html("Hello world - this was inserted using jQuery.");
    }
});
icktoofay
Wow!!!.. pretty easy!.. and I was just like looking at it.... cool thanks..
Reigel
+1  A: 

How about:

setTimeout(changeit, 1000);
Matchu
+1 for the help... thanks!
Reigel
+1  A: 

Do this:

$(function() {
  setTimeout(changeit, 1000);
});

function changeit() {
  $('#hello').html('Hello World - this was inserted using jQuery');
}

or this:

$(function() {
  setTimeout(changeit, 1000);
  function changeit() {
    $('#hello').html('Hello World - this was inserted using jQuery');
  }
});

The problem with your version is that you're passing a string to setTimeout() which is eval'ed but by that time changeit() is out of scope so it won't work.

The alternative is to make changeit global (as per the first code snippet).

cletus
+1 for the help... thanks!
Reigel