Reigel Gallarde
Reigel Gallarde

Reputation: 65254

Using setTimeout() in jquery

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?

Upvotes: 2

Views: 273

Answers (3)

cletus
cletus

Reputation: 625017

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

Upvotes: 1

Matchu
Matchu

Reputation: 85794

How about:

setTimeout(changeit, 1000);

Upvotes: 1

icktoofay
icktoofay

Reputation: 129001

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.");
    }
});

Upvotes: 4

Related Questions