0

I have a function to do something on onClick event.

function onDocumentMouseUp( event ) {
    createsprite(clickedposition);
}

createsprite(clickedposition) {
  var sprite = JSONSPITE // this add correctly sprite to my scene;
  //// here timer function 1 sec
  setTimeout(function(){ remove(sprite); }, 1000);
}

Everything works correctly. But when i click more than once, i have still my variable sprite as a last added one. (yes i know that is correct). And logically remove() have affected only that last one.

What is the correct solution to handle work with unknown amount of same variables. Purpose it too remove each sprite after one second after click one by one in the order of creation.

How can i reach only one variable in the same function, even when there are more variables with the same name on each function init.

2
  • 3
    You just have to var your sprite variable in createsprite Commented Dec 15, 2014 at 15:01
  • sory i forgot, yes i have set VAR sprite variable for the local scope. Added to question. Commented Dec 15, 2014 at 15:09

1 Answer 1

1

You have defined sprite as a global variable. It will exist not only in that function, but is created on the window object.

If you want to remove only the sprite you created in that function, you should make it a variable

var sprite = JSONSPITE; // typo?

This way, the scope of the sprite variable is just that function.

EDIT: OP has changed their question, making the previous explanation seem obsolete

If you want to create multiple sprites, and store them somewhere so you can access them before they are deleted, you might want to create an array of sprites.

sprites = [];

function onDocumentMouseUp( event ) {
    createsprite(clickedposition);
}

function createsprite(clickedposition) {
  sprites.push(JSONSPITE); // Adds the current sprite to the end of the array
  setTimeout(function(){
    var firstSprite = sprites.shift(); // Takes the first sprite out of the array
    remove(firstSprite); 
  }, 1000);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thx that sholud be solution! is there any way with using scope? Because that will not work correct when the Timeout time will be relative, for example by distance vector.
If you want custom timeout times just use it as explained in the first part of my answer, for example: 'var sprite = JSONSPITE;' and remove it like 'setTimeout(function() { remove(sprite); }, sprite.distance);'

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.