pmain8
pmain8

Reputation: 166

Manipulating an object in a setTimeout function that was created by a previous setTimeout function

I have a function to perform an animation using setTimeout functions, structured as follows:

animation: function() {
  //first
  setTimeout(function(){
    makeObject({ ... }); // this makes '#object .secondary' on the DOM
  }, 500);
  //second
  setTimeout(function(){
    ...
  }, 1000);
  //third
  setTimeout(function(){
    $('#object .secondary').doSomething();
  }, 1500);

}

I am creating an object associated with the '.secondary' CSS class in the first setTimeout function, then I am trying to select the object and manipulate it using the class name in the third function. However, the object remains unchanged after the third function executes, and I receive the error "Undefined is not a function". I think this is due to the fact that the setTimeouts execute at the same time, so the secondary object does not yet exist to be selected by the third function. So my question is this: how do I manipulate the secondary object from the third setTimeout function?

Upvotes: 1

Views: 46

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

The timeouts on their own shouldn't be an issue. The 3rd will start around 1 second after the 1st.

But, the error you mentioned would be. Based on your comment:

The calls are actually d3 via d3.select('#object').selectAll('.secondary').fadeOut(50);

It's because D3's Selections, that d3.select() and .selectAll() return, aren't related to jQuery and won't have its methods.

You'll have to either convert the collection from d3 to jQuery before using .fadeOut().

jQuery( d3.select('#object').selectAll('.secondary') ).fadeOut(50);

Or, use jQuery throughout the statement, as you'd suggested doing in your snippet:

jQuery('#object .secondary').fadeOut(50);

Upvotes: 1

tillz
tillz

Reputation: 2108

How about setting the 2nd&3rd Timeout in the previous one? E.G.

animation:function() {
setTimeout(function() {
 makeObject(…);
 setTimeout(function() {
  ...
  setTimeout(function() {
   $('#object .secondary').doSomething();
  },500);
 },500);
},500);
};

Upvotes: 0

Related Questions