JacobTheDev
JacobTheDev

Reputation: 18560

Can't change HTML after timeout

For some reason I can't change HTML after a javascript timeout. Here's the code I'm using:

setTimeout("$(\"#display p\").html(newDescription);", 250);

Is there something wrong with this? If I remove the timeout, the script works perfectly. Here's that version:

$("#display p").html(newDescription);

I'm running Chrome 22 if that makes any difference

Upvotes: 0

Views: 162

Answers (2)

prodigitalson
prodigitalson

Reputation: 60413

yes the first argument should be function.

var newDescription = 'The Description';
setTimeout(function(){
  $("#display p").html(newDescription);
}, 250);

OR

var newDescription = 'The Description',
    myfunc = function(){
       $("#display p").html(newDescription);
    };

setTimeout(myFunc, 250);

Additionally newDescription must be in a scope accessible to your function.

Upvotes: 5

Mattias Buelens
Mattias Buelens

Reputation: 20179

When passing a string to setTimeout, the code is evaluated in the global scope. More than likely, newDescription is a local variable and thus unavailable when the code gets evaluated after the 250 ms timeout.

You shouldn't ever pass strings to setTimeout(), for the same reasons you shouldn't use eval(). By passing a function, you retain your scoped variables and you get better performance as the JavaScript engine can optimize your function (whereas it's not possible to optimize code in a string argument).

var newDescription = "My fancy new description";
setTimeout(function(){
    $("#display p").html(newDescription);
}, 250);

Upvotes: 2

Related Questions