Question Overflow
Question Overflow

Reputation: 11275

How to delete the property of a function from within an anonymous function?

I have the following function which cannot be run concurrently:

function foo()
{
 if(this.running) return;
 this.running = true;
 setTimeout(function() {
  // Do Something
  delete this.running;
 }, 5000);
}

The above seems to work, but when I check the value of this within the anonymous function, it is pointing to Window. I am not sure if this is proper or correct method to delete the property. Can anyone advise why this is working?

Upvotes: 0

Views: 61

Answers (1)

Hilmi
Hilmi

Reputation: 3441

Yes that is correct because the object that invokes the anonymous function you provided in the setTimepout is the window object, to save a closure variable with the value of this just do the following:

function foo()
{
 if(this.running) return;
 this.running = true;
 var self=this;
 setTimeout(function() {
  // Do Something
  delete self.running;
 }, 5000);
}

Update:

When you run foo function that was executed from X object (has X as this), it invokes the content of the function sequentially until it runs setTimeout function, this function adds the anonymous function under the sleep queue the execution will continue executing the foo function with X object,

when each element in the sleep queue passes his timeout time, it will be invoked under the window object for all of them.

Upvotes: 2

Related Questions