Question

i have the 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) { /* Do 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 is set to 3000 miliseconds. my problem is that i want to posting() function to show the table on the screen (its kind of a "loading" screen) and then to pause the script. in actual fact, from some reason the script first pausing, and only after it finishes, it show me the loading screen... how come ?

Was it helpful?

Solution

Browsers run JavaScript and rendering all on one thread. So all three of your JS functions will finish before the page is updated. This is why you should never implement a pause function in JS that is based on a while loop and checking the time. Instead you need to use setTimeout() and put any code that needs to run after the pause in the callback you pass to setTimeout().

Using your example code:

posting();
setTimeout(function() {
    postSent(postUrl, fields);
}, 3000);

OTHER TIPS

There is no sleep or pause function in native javascript. But we can achieve like this.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

I created fiddle at: http://jsfiddle.net/6DQBP/

Script taken from: http://www.phpied.com/sleep-in-javascript/

I found this url's after i answered. Might be useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top