Javascript/JQuery:需要一个时间延迟

Javascript/JQuery : Need a time Delay

本文关键字:一个 时间延迟 JQuery Javascript      更新时间:2023-09-26

我试图实现一个jquery函数,显示一个人的年龄。此代码位于http://keith-wood.name/countdown.html

到目前为止我所拥有的工作,如果我取消警告函数的注释,但不是没有它。我已经尝试了javascript setTimeout函数,但它不会等待并立即执行。如果我用setTimeout和警报运行它,弹出窗口会直接弹出。

如何以及在哪里实现延迟,以便在执行填充它的代码之前加载html元素。

function myAgeLoaded( ) {
    var austDay = new Date();
    austDay = new Date( 1960, 7-1, 18 );
    $( "#defaultCountdown" ).countdown({since: austDay, format: 'YOWDHMS'}).delay( 1500 );
}
function display_text( which )
{
    $.post( "display.php", { content_changed : 1, which : which }, function( data ){ document.getElementById( "main_text" ).innerHTML = html =  data }, "html" );
    if( which == 'abt' ){
//      alert( which );
        myAgeLoaded();
    }
    return false;
}

警报会起作用,因为它推迟了代码的执行,所以在你点击弹出之前,我收到了数据,这就起到了延迟的作用,然而,你的互联网太慢,或者你点击它的速度太快,它可能不起作用。

从jQuery.post()中,你可以看到你传入的第三个参数,是一个函数,它将在请求成功后执行,你也应该在你将数据插入页面后执行myAgeLoaded。因此,myAgeLoaded应该保证在此之后看到#defaultCountdown

function myAgeLoaded( ) {
    var austDay = new Date();
    austDay = new Date( 1960, 7-1, 18 );
    $( "#defaultCountdown" ).countdown({since: austDay, format: 'YOWDHMS'}).delay( 1500 );
}
function display_text( which ) {
    $.post("display.php", {
          content_changed : 1, 
          which : which
          }, 
          // This is the success callback, it'll be called when the request is
           // response with success code and data.
          function( data ) { 
              document.getElementById( "main_text" ).innerHTML = html =  data;
              // Now the page should be filled with content, call the func now.
              if (which === 'abt') {
                myAgeLoaded();
              }
          }, "html");
    return false;
}