0

I'm working with some code that does this:

var _init = false;

this.init = function(){

    if(_init)
        return;
    else
        _init = true;

    // Do a bunch of stuff here
}

It seems to me that there is a tiny race condition there that I'd like to eliminate. It's possible for a second instance of the init function to start running before the first instance has gotten around to setting _init to true. Unlikely, but non-zero, yes?

Given that, is there a straightforward way to eliminate this race condition short of something like a Singleton pattern?

Trott
  • 66,479
  • 23
  • 173
  • 212
  • 2
    Since javascript is single threaded, there is only one thread of execution at any given time so nothing else can call your function while you're testing the `_init` variable. – jfriend00 Oct 05 '11 at 19:52

2 Answers2

4

javascript is single threaded (ignoring web-workers for the moment) so you should be ok -- there should be no race conditions.

I think the "standard" way of doing this, however, would be to use a self-invoking function

(function(){
    // init stuff here, but you don't need to have any of the _init stuff
})() // <-- this causes your function to be invoked immediately
jfriend00
  • 683,504
  • 96
  • 985
  • 979
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
0

One easy way to ensure the function runs only once is simply to delete the method at the end:

this.init = function(){
    // Do a bunch of stuff here

    // now delete:
    delete this.init;
}

or you could reassign the property to a no-op, if you need to be able to call it again:

this.init = function(){
    // Do a bunch of stuff here

    this.init - function() {};
}

But this only ensures that the function runs once per instance - if you need it to only run once, ever, your flag-based approach is probably better, and as other posters have suggested, your worries about a race condition are unfounded with single-threaded code.

nrabinowitz
  • 55,314
  • 10
  • 149
  • 165