0

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 ?

Asaf Nevo
  • 11,338
  • 23
  • 79
  • 154
  • That is not a pause, just use a `setTimeout` – Esailija Mar 08 '12 at 09:42
  • but setTimeout doesn't stop my script.. i want my script to completely stop and wait the time i've setted – Asaf Nevo Mar 08 '12 at 09:44
  • This doesn't stop your script - your script is calculating dates for 3 seconds for no reason at all. Because this script is using all resources available for the page, nothing else can happen - everything will be frozen. – Esailija Mar 08 '12 at 09:49

2 Answers2

2

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);
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • ok but after the postSent function i have : `postSent(postUrl, fields);` `if(isPostSent)` `{` `updatePostPicture(true);` `}` `else` `{` `updatePostPicture(false);` `}` `}` `document.getElementById('post_close').style.visibility = "visible"; ` where should i put it to wait while pausing ? – Asaf Nevo Mar 08 '12 at 09:51
  • _Everything_ that you want to run after the pause should go in the function you pass to `setTimeout()` (or in functions that you call from there). In your case you're also using `$.ajax()` so it might be more appropriate to put some or all of that code in the Ajax success callback (though I notice you don't seem to have a success callback, just an error callback, which I find a little odd if you want to do something after confirming that the request went through). – nnnnnn Mar 08 '12 at 09:56
  • what should i do if the setTimeout is inside a for loop ? `for (var i = 0; i – Asaf Nevo Mar 08 '12 at 11:16
-1

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.

Community
  • 1
  • 1
arunes
  • 3,464
  • 2
  • 21
  • 31
  • If you take another look at the question you'll see that the OP's `pause()` function is similar to your `sleep()` function except that yours will end either when the for loop runs out or when the specified number of milliseconds has passed, whichever comes first. You should _never_ code something like this in JS because it locks up the browser until the pause is over (and if you try to make the pause too long the browser will actually interrupt it with a prompt to the user asking if they want to cancel the long-running script). You have to restructure the code to use `setTimeout()` instead. – nnnnnn Mar 08 '12 at 09:51
  • Thanks and yes i'm aware of it. I dont recommend this technique, your solution is way better than this. But i think @Asaf Nevo looking something like i posted. – arunes Mar 08 '12 at 09:52
  • This is exactly the same as "pause" in the OP except worse :o – Esailija Mar 08 '12 at 09:57