Home  >  Q&A  >  body text

Problem with location.reload - Stack Overflow

start.onclick=function newGame(){
    location.reload();
    flag = selectModel[0];
    console.log(flag);
};

I originally wanted to refresh the page and assign the global variable flag after clicking. Successfully refreshed, but failed to assign value successfully; if location.reload is commented out, value can be assigned.

Is location.reload() asynchronous? When the value is assigned, the refresh has not yet been executed, but the refresh operation is performed after the assignment is completed. Is this true?

给我你的怀抱给我你的怀抱2713 days ago1195

reply all(3)I'll reply

  • 習慣沉默

    習慣沉默2017-05-18 10:53:54

    You first need to understand the life cycle of javascript in the browser.

    After reloading the page and entering the next life cycle, the flag assigned in the previous cycle will be destroyed even if the assignment is successful.

    Refreshing the page is equivalent to throwing everything away and starting over, just like reopening the page.

    What weird requirement would require you to modify the global flag after clicking a link to refresh?

    reply
    0
  • 怪我咯

    怪我咯2017-05-18 10:53:54

    You can save this flag to localdtorage

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-18 10:53:54

    It should be synchronized, so a better way is to consider this:

    start.onclick=function newGame(){
        flag = selectModel[0];
        console.log(flag);
        setTimeout(() => {
            location.reload();
        });
    };

    reply
    0
  • Cancelreply