0
votes

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

3
When you pass a String to setTimeout() or setInterval(), it'll be evaluated in the global scope, where json isn't available.Jonathan Lonowski

3 Answers

3
votes

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

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

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);
0
votes

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