0

I have a var in jquery after a request like

         type: 'POST',
     data: data,
     cache: false,
     success: function (data) {
         var json = jQuery.parseJSON(data);

I'm trying to use timeout to fire the function below after five seconds.

        $("#a" + json.id).fadeOut(300);

At the moment I'm doing

          setTimeout('$("#a" + json.id).fadeOut(300)', 500);

but it doesn't seem to work

1
  • 1
    When you pass a String to setTimeout() or setInterval(), it'll be evaluated in the global scope, where json isn't available. Commented Jan 19, 2014 at 3:52

3 Answers 3

3

setTimeout takes a function and a number as a parameter, try this:

setTimeout(function() {
    $("#a" + json.id).fadeOut(300);
}, 500);
Sign up to request clarification or add additional context in comments.

2 Comments

Firebug says typeError: ("#a" + json.id).fadeOut is not a function
See my edit, I forgot to put a $ in front of ("#a" + json.id).fadeOut(300)
0

Not sure if the value of json.id changes by the time the timeout callback is called.

Consider the following example:

for (var i=0;i<10;i++){
  setTimeout(function(){console.log(i)},500);
}

The callback function sees i=10 because that's the value of i by the time the function is invoked. You can do a pre-binding by using closure:

var f=function(id){
  setTimeout(function(){console.log(id);},500);
}

for (var i=0;i<10;i++) f(i);

Now that you see how closure and pre-binding work, here's a more robust solution to your question:

var f=function(id){
  setTimeout(function(){$('#a'+id).fadeOut(300);},500);
}

f(json.id);

Comments

0

Your code doesn't work because the String is eval'ed in global context. So for it to work you can make json global (remove the var).

Also, while I am not sure where you are calling the setTimeout from, but assuming it is inside the callback, you can alternatively make the id a part of the string :


setTimeout('$("#a'+json.id+'").fadeOut(300)', 500);

But certainly a better option is to avoid eval and globals at all costs (checkout Eval is evil and Why global state is the devil for an elaborate explaination) and pass in a closure :


setTimeout(function(){ $("#a" + json.id).fadeOut(300); }, 500);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.