Search code examples
javascriptsettimeout

updating attribute value of a object from within a setTimeout function in Javascript


I am having trouble with the following snippet of code.

 var flag = { f: 0 };
 setTimeout(function(flag) {
    flag.f+=1;
 }, duration, flag);
 while(flag.f == 0);
 alert("Asd");

"Asd" is never alerted. The page crashes after sometime. What is wrong with it ?


Solution

  • setTimeout() halts the execution of the rest of your code. setTimeout() will run, then your while loop will run so it never executes.

    This is a very dumbed down version of what is actually happening. For more info:

    http://ejohn.org/blog/how-javascript-timers-work/

    EDIT:

    after better undertsanding your question it seems this is what you are looking for:

    var flag = { f: 0 };
     setTimeout(function(flag) {
        flag.f+=1;
        afterMove()
    
     }, duration, flag);
    
    function afterMove() {
       alert("move is done!");
    }