152

I need to create a function which can be executed only once, in each time after the first it won't be executed. I know from C++ and Java about static variables that can do the work but I would like to know if there is a more elegant way to do this?

vlio20
  • 8,955
  • 18
  • 95
  • 180
  • ~8 years later I created a feature request to my decorators lib (https://github.com/vlio20/utils-decorators) to have a decorator which will do exactly that (https://github.com/vlio20/utils-decorators/issues/77) – vlio20 Jul 02 '20 at 19:32

32 Answers32

305

If by "won't be executed" you mean "will do nothing when called more than once", you can create a closure:

var something = (function() {
    var executed = false;
    return function() {
        if (!executed) {
            executed = true;
            // do something
        }
    };
})();

something(); // "do something" happens
something(); // nothing happens

In answer to a comment by @Vladloffe (now deleted): With a global variable, other code could reset the value of the "executed" flag (whatever name you pick for it). With a closure, other code has no way to do that, either accidentally or deliberately.

As other answers here point out, several libraries (such as Underscore and Ramda) have a little utility function (typically named once()[*]) that accepts a function as an argument and returns another function that calls the supplied function exactly once, regardless of how many times the returned function is called. The returned function also caches the value first returned by the supplied function and returns that on subsequent calls.

However, if you aren't using such a third-party library, but still want a utility function (rather than the nonce solution I offered above), it's easy enough to implement. The nicest version I've seen is this one posted by David Walsh:

function once(fn, context) { 
    var result;
    return function() { 
        if (fn) {
            result = fn.apply(context || this, arguments);
            fn = null;
        }
        return result;
    };
}

I would be inclined to change fn = null; to fn = context = null;. There's no reason for the closure to maintain a reference to context once fn has been called.

Usage:

function something() { /* do something */ }
var one_something = once(something);

one_something(); // "do something" happens
one_something(); // nothing happens

[*] Be aware, though, that other libraries, such as this Drupal extension to jQuery, may have a function named once() that does something quite different.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 1
    works very good , can you explain the login behind it , how does var executed = false; works – Amr.Ayoub Oct 21 '17 at 13:00
  • 2
    @EgyCode - This is explained nicely in the [MDN documentation on closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). – Ted Hopp Oct 21 '17 at 23:48
  • sorry , I meant logic , I never understood boolean var and how it works in that case executed – Amr.Ayoub Oct 30 '17 at 03:13
  • 2
    @EgyCode - In certain contexts (like in an `if` statement test expression), JavaScript expects one of the values `true` or `false` and the program flow reacts according to the value found when the expression is evaluated. Conditional operators like `==` always evaluate to a boolean value. A variable can also hold either `true` or `false`. (For more info, see the documentation on [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean), [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), and [falsey](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).) – Ted Hopp Oct 30 '17 at 03:31
  • I don't understand why executed is not reset with every new call. Can someone explain it, please? – Juanse Cora Oct 08 '19 at 10:06
  • @JuanseCora - The outer function (where `executed` is initialized) is only executed once--when `something` is initialized. Note the `()` at the end of the statement that initialized `something`. That causes the outer function to be called and `something` is initialized with the *inner* function that is returned. Thus, each time `something` is called, only the inner function runs. – Ted Hopp Oct 08 '19 at 14:38
  • This code seems to assume that you have somewhere that you can run the code that initializes the `something` method and have it only run once. If you put all that code in a call interceptor, then it will re-set and run first call to `something` each time it is all called. – Vaccano Oct 20 '21 at 18:19
  • @Vaccano - I'm not sure I understand your point. Are you talking about passing the initializer expression for I used for `something` directly into `window.setInterval()` or the like? That should work. The expression evaluates to a closure that is not reset each time. If you have something else in mind, please elaborate. – Ted Hopp Oct 20 '21 at 20:15
  • @TedHopp - Sorry for the confusion. I asked a separate question here that explains it better: https://stackoverflow.com/questions/69651360/run-javascript-code-only-once-and-with-only-one-spot-to-put-the-code I was able to deal with it by using local storage. – Vaccano Oct 20 '21 at 21:08
  • 1
    @Vaccano - Okay. Now I understand what you were asking, and I'm glad you found a solution. The local storage solution is a form of global variable (although at first glance it may not seem like it). Many other answers here use something like that. I see no reason to combine a global variable approach with a closure (as the answer to your question by Reflective suggests.) – Ted Hopp Oct 21 '21 at 00:52
  • here is a func that can be called only twice: ` let bucketWith2Apples = (function () { let counter = 0; return function () { ++counter; if (counter <= 2) { console.log("here is an apple"); // logic here that can be called only twice return; } else { console.log("no more apples left"); } }; })(); bucketWith2Apples(); // here is an apple bucketWith2Apples(); // here is an apple bucketWith2Apples(); // no more apples left bucketWith2Apples(); // no more apples left bucketWith2Apples(); // no more apples left ` – human Sep 04 '22 at 13:59
72

Replace it with a reusable NOOP (no operation) function.

// this function does nothing
function noop() {};

function foo() {
    foo = noop; // swap the functions

    // do your thing
}

function bar() {
    bar = noop; // swap the functions

    // do your thing
}
Margus
  • 19,694
  • 14
  • 55
  • 103
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • Why the down vote? What's the problem? This prevents the need to create a new flag for every function. – I Hate Lazy Oct 03 '12 at 17:25
  • There are more elegant ways of achieving the intended functionality; check asawyer or hakra responses – fableal Oct 03 '12 at 17:27
  • 14
    @fableal: How is this inelegant? Again, it is very clean, requires less code, and doesn't require a new variable for every function that should be disabled. A *"noop"* is designed exactly for this sort of situation. – I Hate Lazy Oct 03 '12 at 17:28
  • 1
    @fableal: I just looked at hakra's answer. So make a new closure and variable every time you need to do this to a new function? You have a very funny definition of "elegant". – I Hate Lazy Oct 03 '12 at 17:30
  • 2
    Accordingly to asawyer's response, you only needed to do _.once(foo) or _.once(bar), and the functions themselves don't need to be aware of being ran only once (no need for the noop and no need for the * = noop). – fableal Oct 03 '12 at 17:31
  • Goodness. That's useful if you want to have two version of the function. If not, `foo=noop;` is hardly a big deal or inelegant. The main point of that code is that the initial return is memoized. That can be useful if that's what is desired. That's not always the case. – I Hate Lazy Oct 03 '12 at 17:43
  • You're right, that was my idea. My "inelegant" comes only from the global `noop()` and one having to write that `foo=noop` in every function intended to run only once. Only my opinion. – fableal Oct 03 '12 at 17:46
  • Would it be wrong to replace bar = noop with bar = function(){}, or bar = null? – user1566694 Jul 16 '14 at 20:58
  • @user1566694 - `bar = function(){};` would create a new function each time it was executed. That's why a global `noop()` function is preferable. Using `bar = null;` would cause an error the next time a function call was attempted, which is far from the desired "does nothing" behavior. – Ted Hopp Feb 11 '15 at 19:47
  • @TedHopp Can you explain "`bar = function(){};` would create a new function each time it was executed"? Surely by replacing bar with `function(){}` the code that creates the function will never be called again and the noop function will be called instead? Just point me in the right direction if my JS fundamentals in this regard are lacking... – JonoCoetzee Jun 10 '15 at 09:52
  • @JonoCoetzee - Yes, you are correct that the code could not be executed more than once for any particular function (e.g., `bar`). However, if several functions needed this treatment, each would be creating its own replacement no-op function. – Ted Hopp Jun 10 '15 at 14:32
  • I would always keep `bar = noop;` at the top of the function, so that it is clearly visible, that if the function name changes, `bar = noop;` must be changed as well. If you keep it at the end of the function and have a big code block in between, you might forget to also rename this line of code, which would make the function callable multiple times again (not only once). This kind of misbehaviour can be extremely difficult to find. – Lionel Jun 27 '15 at 08:01
  • 7
    Not really the best solution. If you're passing this function as a callback, it can still be called multiple times. For example: `setInterval(foo, 1000)` - and already this doesn't work anymore. You're just overwriting the reference in the current scope. – a cat Mar 28 '16 at 07:43
  • 1
    Reusable `invalidate` function which works with `setInterval` etc,.: https://jsbin.com/vicipar/1/edit?js,console – Monday Fatigue Apr 27 '17 at 23:41
  • Trying to assign to a function reference will only work if the function is in the same file, not if it was imported from another file, you would only be changing your local reference to `bar` in this case – Ruan Mendes Sep 14 '21 at 19:18
49

Point to an empty function once it has been called:

function myFunc(){
     myFunc = function(){}; // kill it as soon as it was called
     console.log('call once and never again!'); // your stuff here
};
<button onClick=myFunc()>Call myFunc()</button>

Or, like so:

var myFunc = function func(){
     if( myFunc.fired ) return;
     myFunc.fired = true;
     console.log('called once and never again!'); // your stuff here
};

// even if referenced & "renamed"
((refToMyfunc)=>{
  setInterval(refToMyfunc, 1000);
})(myFunc)
Community
  • 1
  • 1
vsync
  • 118,978
  • 58
  • 307
  • 400
  • 3
    This solution is much more in the spirit of a highly dynamic language like Javascript. Why set semaphores, when you can simply empty the function once it has been used? – Ivan Čurdinjaković Dec 10 '14 at 06:48
  • Very nice solution! This solution is also performing better than the closure approach. The only minor "drawback" is that you need to keep the function name in sync if the name changes. – Lionel Jun 26 '15 at 14:07
  • 8
    The problem with this is that if there's another reference to the function somewhere (e.g. it was passed as an argument and stashed in another variable somewhere -- as in a call to `setInterval()`) then the reference will repeat the original functionality when called. – Ted Hopp Apr 05 '16 at 17:31
  • @TedHopp - [here's](http://jsbin.com/zujosinupe/edit?js,console,output) a special treatment for those cases – vsync Apr 05 '16 at 18:18
  • 1
    Yes, that's exactly like [Bunyk's answer](http://stackoverflow.com/a/35984663/535871) on this thread. It's also similar to a closure (as in [my answer](http://stackoverflow.com/a/12713611/535871)) but using a property instead of a closure variable. Both cases are quite different from your approach in this answer. – Ted Hopp Apr 05 '16 at 18:57
26

UnderscoreJs has a function that does that, underscorejs.org/#once

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      memo = func.apply(this, arguments);
      func = null;
      return memo;
    };
  };
asawyer
  • 17,642
  • 8
  • 59
  • 87
  • 1
    It seems funny to me to have `once` accept arguments. You could do `squareo = _.once(square); console.log(squareo(1)); console.log(squareo(2));` and get `1` for both calls to `squareo`. Am I understanding this right? – aschmied Sep 09 '16 at 14:34
  • @aschmied You are correct - the result of the first call's set of arguments will be memomized and returned for all other calls regardless of the parameter as the underlying function is never called again. In cases like that I do not suggest using the `_.once` method. See https://jsfiddle.net/631tgc5f/1/ – asawyer Sep 09 '16 at 15:08
  • 1
    @aschmied Or I guess use a separate call to once per argument set. I don't think this is really intended for that sort of use. – asawyer Sep 09 '16 at 15:35
  • 1
    Handy if you're already using `_`; I wouldn't recommended depending upon the entire library for such a small bit of code. – Joe Shanahan Dec 15 '16 at 09:34
13

Talking about static variables, this is a little bit like closure variant:

var once = function() {
    if(once.done) return;

    console.log('Doing this once!');

    once.done = true;
};

once(); // Logs "Doing this once!"
once(); // Logs nothing

You could then reset a function if you wish:

once.done = false;
once(); // Logs "Doing this once!" again
Bunyk
  • 7,635
  • 8
  • 47
  • 79
6

You could simply have the function "remove itself"

​function Once(){
    console.log("run");

    Once = undefined;
}

Once();  // run
Once();  // Uncaught TypeError: undefined is not a function 

But this may not be the best answer if you don't want to be swallowing errors.

You could also do this:

function Once(){
    console.log("run");

    Once = function(){};
}

Once(); // run
Once(); // nothing happens

I need it to work like smart pointer, if there no elements from type A it can be executed, if there is one or more A elements the function can't be executed.

function Conditional(){
    if (!<no elements from type A>) return;

    // do stuff
}
Shmiddty
  • 13,847
  • 1
  • 35
  • 52
  • 1
    I need it to work like smart pointer, if there no elements from type A it can be executed, if there is one or more A elements the function can't be executed. – vlio20 Oct 03 '12 at 17:31
  • @VladIoffe That's not what you asked. – Shmiddty Oct 03 '12 at 17:32
  • This won't work if `Once` is passed as a call-back (e.g., `setInterval(Once, 100)`). The original function will continue to be called. – Ted Hopp Feb 27 '19 at 15:05
5
var quit = false;

function something() {
    if(quit) {
       return;
    } 
    quit = true;
    ... other code....
}
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
3

simple decorator that easy to write when you need

function one(func) {
  return function () {
     func && func.apply(this, arguments);
     func = null;
  }
}

using:

var initializer= one( _ =>{
      console.log('initializing')
  })

initializer() // 'initializing'
initializer() // nop
initializer() // nop
pery mimon
  • 7,713
  • 6
  • 52
  • 57
3

I'm using typescript with node and it was @I Hate Lazy's answer that inspired me. I just assigned my function to a noop function.

let printName = (name: string) => {
    console.log(name)
    printName = () => {}
}

printName('Sophia') // Sophia
printName('Nico')   // Nothing Happens

https://jsbin.com/yuzicek/edit?js,console

djsd123
  • 383
  • 1
  • 4
  • 8
2

try this

var fun = (function() {
  var called = false;
  return function() {
    if (!called) {
      console.log("I  called");
      called = true;
    }
  }
})()
Database_Query
  • 626
  • 4
  • 14
2

From some dude named Crockford... :)

function once(func) {
    return function () {
        var f = func;
        func = null;
        return f.apply(
            this,
            arguments
        );
    };
}
Jowen
  • 5,203
  • 1
  • 43
  • 41
  • 2
    This is great if you think that `TypeError: Cannot read property 'apply' of null` is great. That's what you get the second time you invoke the returned function. – Ted Hopp Apr 23 '18 at 18:44
2

Reusable invalidate function which works with setInterval:

var myFunc = function (){
  if (invalidate(arguments)) return;
  console.log('called once and never again!'); // your stuff here
};

const invalidate = function(a) {
  var fired = a.callee.fired;
  a.callee.fired = true;
  return fired;
}

setInterval(myFunc, 1000);

Try it on JSBin: https://jsbin.com/vicipar/edit?js,console

Variation of answer from Bunyk

Monday Fatigue
  • 223
  • 1
  • 3
  • 19
1

Here is an example JSFiddle - http://jsfiddle.net/6yL6t/

And the code:

function hashCode(str) {
    var hash = 0, i, chr, len;
    if (str.length == 0) return hash;
    for (i = 0, len = str.length; i < len; i++) {
        chr   = str.charCodeAt(i);
        hash  = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
}

var onceHashes = {};

function once(func) {
    var unique = hashCode(func.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1]);

    if (!onceHashes[unique]) {
        onceHashes[unique] = true;
        func();
    }
}

You could do:

for (var i=0; i<10; i++) {
    once(function() {
        alert(i);
    });
}

And it will run only once :)

Aldekein
  • 3,538
  • 2
  • 29
  • 33
1

Initial setup:

var once = function( once_fn ) {
    var ret, is_called;
    // return new function which is our control function 
    // to make sure once_fn is only called once:
    return function(arg1, arg2, arg3) {
        if ( is_called ) return ret;
        is_called = true;
        // return the result from once_fn and store to so we can return it multiply times:
        // you might wanna look at Function.prototype.apply:
        ret = once_fn(arg1, arg2, arg3);
        return ret;
    };
}
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
1

If your using Node.js or writing JavaScript with browserify, consider the "once" npm module:

var once = require('once')

function load (file, cb) {
  cb = once(cb)
  loader.load('file')
  loader.once('load', cb)
  loader.once('error', cb)
}
orcaman
  • 6,263
  • 8
  • 54
  • 69
1

If you want to be able to reuse the function in the future then this works well based on ed Hopp's code above (I realize that the original question didn't call for this extra feature!):

   var something = (function() {
   var executed = false;              
    return function(value) {
        // if an argument is not present then
        if(arguments.length == 0) {               
            if (!executed) {
            executed = true;
            //Do stuff here only once unless reset
            console.log("Hello World!");
            }
            else return;

        } else {
            // otherwise allow the function to fire again
            executed = value;
            return;
        }       
    }
})();

something();//Hello World!
something();
something();
console.log("Reset"); //Reset
something(false);
something();//Hello World!
something();
something();

The output look like:

Hello World!
Reset
Hello World!
CMP
  • 1,170
  • 12
  • 11
1

A simple example for turning on light only once.

function turnOnLightOnce() {
  let lightOn = false;

  return function () {
    if (!lightOn) {
      console.log("Light is not on...Turning it on for first and last time");
      lightOn = true;
    }

  };
}

const lightOn = turnOnLightOnce();
lightOn()  // Light is not on...Turning it on for first and last time
lightOn()
lightOn()
lightOn()
lightOn()

https://codesandbox.io/s/javascript-forked-ojo0i?file=/index.js

This happens due to closure in JavaScript.

Sandeep Amarnath
  • 5,463
  • 3
  • 33
  • 43
1
function once (fn1) {
  var ran = false
  var memo = null
  var fn = function(...args) {
    if(ran) {return memo}
    ran = true
    memo = fn1.apply(null, args)
    return memo
  }
  return fn
}
NIsham Mahsin
  • 340
  • 5
  • 18
1

FOR EVENT HANDLER

If the function is a callback for an event listener, there is already a built-in option in the addEventListner method for just executing the callback once.

It can accept 3 parameters

  • Type
  • callback
  • options

options is an object that has a property called once

ex:

const button = document.getElementById('button');

const callbackFunc = () => {
  alert('run')
}

button.addEventListener('click', callbackFunc, { once: true }) 
<button id="button">Click Once</button>
Mina
  • 14,386
  • 3
  • 13
  • 26
0

Trying to use underscore "once" function:

var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.

http://underscorejs.org/#once

Andrew Feng
  • 1,912
  • 17
  • 20
0
var init = function() {
    console.log("logges only once");
    init = false;
}; 

if(init) { init(); }

/* next time executing init() will cause error because now init is 
   -equal to false, thus typing init will return false; */
RegarBoy
  • 3,228
  • 1
  • 23
  • 44
0
if (!window.doesThisOnce){
  function myFunction() {
    // do something
    window.doesThisOnce = true;
  };
};
atw
  • 5,428
  • 10
  • 39
  • 63
  • It's a bad practice to pollute the global scope (a.k.a window) – vlio20 Feb 12 '16 at 19:09
  • 1
    I agree with you but someone might get something out of it. – atw Feb 12 '16 at 19:12
  • 1
    This doesn't work. When that code is first executed, the function is created. Then when the function is called it is executed and the global is set to false, but the function can still be called a next time. – trincot Feb 12 '16 at 21:30
  • It is not set to false anywhere. – atw Feb 12 '16 at 22:25
0

If you're using Ramda, you can use the function "once".

A quote from the documentation:

once Function (a… → b) → (a… → b) PARAMETERS Added in v0.1.0

Accepts a function fn and returns a function that guards invocation of fn such that fn can only ever be called once, no matter how many times the returned function is invoked. The first value calculated is returned in subsequent invocations.

var addOneOnce = R.once(x => x + 1);
addOneOnce(10); //=> 11
addOneOnce(addOneOnce(50)); //=> 11
David
  • 2,528
  • 1
  • 23
  • 29
0

keep it as simple as possible

function sree(){
  console.log('hey');
  window.sree = _=>{};
}

You can see the result

script result

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57
Sreeketh K
  • 21
  • 4
0

JQuery allows to call the function only once using the method one():

let func = function() {
  console.log('Calling just once!');
}
  
let elem = $('#example');
  
elem.one('click', func);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p>Function that can be called only once</p>
  <button id="example" >JQuery one()</button>
</div>

Implementation using JQuery method on():

let func = function(e) {
  console.log('Calling just once!');
  $(e.target).off(e.type, func)
}
  
let elem = $('#example');
  
elem.on('click', func);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p>Function that can be called only once</p>
  <button id="example" >JQuery on()</button>
</div>

Implementation using native JS:

let func = function(e) {
  console.log('Calling just once!');
  e.target.removeEventListener(e.type, func);
}
  
let elem = document.getElementById('example');
  
elem.addEventListener('click', func);
<div>
  <p>Functions that can be called only once</p>
  <button id="example" >ECMAScript addEventListener</button>
</div>
Nikita
  • 1
0

Tossing my hat in the ring for fun, added advantage of memoizing

const callOnce = (fn, i=0, memo) => () => i++ ? memo : (memo = fn());
// usage
const myExpensiveFunction = () => { return console.log('joe'),5; }
const memoed = callOnce(myExpensiveFunction);
memoed(); //logs "joe", returns 5
memoed(); // returns 5
memoed(); // returns 5
...
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
0

You can use IIFE. IIFE means Immediately Invoked Function Expression and the result is to call a function only once by the time is created. Your code will be like this:

(function () {
  //The code you want to execute only one time etc...
  console.log("Hello world");
})()

Additionally, this way the data in the function remains encapsulated.
Of course and you can return values from the function and stored them into a new variable, by doing:

const/let value = (function () {
  //The code you want to execute only one time etc...
  const x = 10;
  return x;
})()
0
function x()
{
  let a=0;
  return function check()
   {
    if(!a++) 
     {
       console.log("This Function will execute Once.")
       return;
      }
     console.log("You Can't Execute it For the Second Time.")
     return;
    }
  }

 z=x()
 z() //Op - This Function will execute once
 z() //OP - You can't Execute it for the second time.
0

I find it useful to just have a simple function that just returns true once, so you can keep the side effects higher up.

let once = () => !! (once = () => false);

once() // true
once() // false

Use like this:

if (once()) {
  sideEffect()
}

This exploits the fact that you can coerce an assignment expression to return true while changing the same function into a function that returns false.

If you must have it execute a function, it can be adapted using a ternary:

let once = (x) => !! (once = () => false) ? x() : false;

Now it accepts a single function as an argument. Fun fact, the second false is never reached.

sfscs
  • 515
  • 4
  • 8
-1
// This is how function in JavaScript can be called only once    

let started = false;     
      if (!started) {
                    start() { // "do something" }
                }
                started = true;
            }
Omar Saade
  • 320
  • 2
  • 8
  • This is how function in JavaScript that can be called only once – Omar Saade Mar 17 '22 at 21:30
  • 1
    You don't even have a function here. – General Grievance Mar 18 '22 at 01:31
  • 2
    See "[Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/128421)". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem. – the Tin Man Mar 22 '22 at 05:04
-2

This one is useful for preventing infinite loops (using jQuery):

<script>
var doIt = true;
if(doIt){
  // do stuff
  $('body').html(String($('body').html()).replace("var doIt = true;", 
                                                  "var doIt = false;"));
} 
</script>

If you're worried about namespace pollution, subsitute a long, random string for "doIt".

Elliot Gorokhovsky
  • 3,610
  • 2
  • 31
  • 56
-2

It helps to prevent sticky execution

var done = false;

function doItOnce(func){
  if(!done){
    done = true;
    func()
  }
  setTimeout(function(){
    done = false;
  },1000)
}
Gleb Dolzikov
  • 776
  • 8
  • 13