www.webdeveloper.com
Results 1 to 3 of 3

Thread: Check if function is finished

  1. #1
    Join Date
    Aug 2013
    Posts
    57

    Check if function is finished

    Hello

    I want a JavaScript (No jQuery/AJAX/...) code which checks if a function has loaded before running other.

    Code:
    //Psuedo code
    function a() {
    //do something
    }
    function b() {
    if (a() == !finished) {
    //Wait until a() has finished
    } else {
    //Actual code for function b()
    }
    }
    Of course that code doesn't work, but how could I achieve something like that?
    In pure JavaScript?

    Thanks for reading,
    Niely

  2. #2
    Join Date
    Nov 2010
    Posts
    1,102
    set a flag, flip the flag at the end of a() and check on the flag in b()

    what you want to do if a() hasn't finished yet is up to you...

    Code:
    var finished =false;
    function a() {
    //some stuff that takes a long time to do
    finished = true;
    }
    
    function b() {
    if (!finished) {
    //either do nothing or put a setInterval to call b() again in a little while
    } else {
    //Actual code for function b()
    }
    }

  3. #3
    Join Date
    Mar 2009
    Posts
    523
    There are various factors and questions here. Why wouldn't one function be loaded? Are they coming from different scripts/sources? Are they functions having global scope?

    Assuming that both function a and function b have global scope, you can always do something like:

    Code:
    function doStart(){
       if(window.a && window.b){
            a();
            b();
        }
       else{
           setTimeout(doStart, 1000);  //the 1000 is arbitrary
       }
    }
    and start the doStart function ASAP

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles