Pregunta

Tengo el siguiente 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;  
 }

El tiempo se establece en 3000 milisegundos. Mi problema es que quiero publicar () Función para mostrar la tabla en la pantalla (su tipo de pantalla de carga ") y luego para pausar el script. De hecho, de alguna razón, el script se detiene primero, y solo después de que finalice, me muestran la pantalla de carga ... ¿Cómo es?

¿Fue útil?

Solución

Los navegadores ejecutan JavaScript y representando todo en un hilo.Por lo tanto, las tres funciones de JS terminarán antes de actualizar la página.Esta es la razón por la que debe nunca implementar una función de pausa en JS que se basa en un bucle de tiempo y verificando la hora.En su lugar, debe usar setTimeout() y coloque cualquier código que tenga que ejecutarse después de la pausa en la devolución de llamada que pasa a setTimeout().

usando su código de ejemplo:

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

Otros consejos

No hay una función de sueño o pausa en JavaScript nativo.Pero podemos lograr así.

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

Fabricé Fiddle en: http://jsfiddle.net/6dqbp/

Script tomado de: http://www.phpied.com/sleep-in-JavaScript /

Encontré esta URL después de que respondí.Podría ser útil.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top