Javascript / JQuery:需要时间延迟

时间:2015-08-02 08:48:57

标签: javascript jquery delay settimeout

我正在尝试实现一个显示一个人年龄的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;
}

1 个答案:

答案 0 :(得分:2)

警报会起作用,因为它推迟了代码执行,所以在你点击弹出窗口之前我收到数据的帖子,这可以作为延迟,但是,你上网太慢,或者你点击它太快了,它可能无法正常工作。

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;
}




相关问题