2

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?

3 Answers 3

4

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.");
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

How about:

setTimeout(changeit, 1000);

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.