javascript pausing a script changes order of appearance -
i have following script:
posting(); pause(time); postsent(posturl, fields); function postsent(posturl, fields) { $.ajax( { url : posturl, type : "post", data : fields, cache : false, error : function(xhr, textstatus, errorthrown) { var answer = xhr.responsetext; answer = answer.split(":"); answer = answer[0].replace(/}/g,"").replace(/{/g,"").replace(/"/g,""); if (answer == "id") { ispostsent = true; } else { ispostsent = false; } } }); } function pause(milliseconds) { var dt = new date(); while ((new date()) - dt <= milliseconds) { /* nothing */ } } function posting() { var table = ''; table += '<table border="0" rules="none" cellpadding="5" style="z-index:+10; position:fixed; top:35%; left:35%; box-shadow: 0px 0px 5px 5px #888888;" rules="none" border="0" bgcolor="#edeff4">'; table += '<td align="center">'; table += '<img src="images/loading.gif" id="post_status_image">'; table += '</td>'; table += '<tr >'; table += '<td align="center">שולח הודעה, אנא המתן...</td>'; table += '</tr>'; table += '<tr>'; table += '<td align="center" id="post_status"></td>'; table += '</tr>'; table += '<tr >'; table += '<td align="center" ><img id="post_close" src="images/close1.png" onclick="closepop()" style="visibility:hidden;"></td>'; table += '</tr>'; table += '</table>'; document.getelementbyid('post').innerhtml = table; }
time set 3000 miliseconds. problem want posting() function show table on screen (its kind of "loading" screen) , pause script. in actual fact, reason script first pausing, , after finishes, show me loading screen... how come ?
browsers run javascript , rendering on 1 thread. 3 of js functions finish before page updated. why should never implement pause function in js based on while loop , checking time. instead need use settimeout()
, put code needs run after pause in callback pass settimeout()
.
using example code:
posting(); settimeout(function() { postsent(posturl, fields); }, 3000);
Comments
Post a Comment