如何创建秒表

时间:2015-05-15 11:17:27

标签: javascript jquery ajax timer

我有一个Ajax调用。像这样:

$(document).on('submit', '#formPropiedades', function(event) {
    event.preventDefault();
    var content = {}, url = "http://www.xxxxyzzz.com/xxx/yyy/web/ajax.php";    
    $("#dialog1").dialog("open");
    var posting = $.post(url, {
        im_core: 'saveAllAdds',
        idFeed: <?php echo $_POST['idFeed'] ?>,
        pais: <?php echo $pais1?>
    }).done(function(data) {
        if (data == 1)
            $(".overlay-bg1").html("Suces....");
        else
            $(".overlay-bg1").html(data);
    }); 
<?php } ?>  
});

我的HHTML看起来像这样:

<div id="dialog1" title="Attention!!" style="width:60%">
    <div class="overlay-bg1">Saving the Adds....</div>
</div>

打开Jquery Ui Dialogue的代码就像这样

$(function () {
    $("#dialog1").dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 1000
        },
        hide: {
            effect: "",
            duration: 1000
        },  
    });
});

我想在POPUP中显示一个计时器,它应该在Ajax调用完成时启动,并在我得到响应时停止。它应该看起来像秒表

3 个答案:

答案 0 :(得分:3)

在ajax开始之前

var startTime = (new Date()).getTime();

当你收到回复时:

var nowTime = (new Date()).getTime();
var theTime = nowTime - startTime;

<强>更新

使用可视化计时器demo

<强>更新

秒和分钟demo

<强>更新

号码为demo

答案 1 :(得分:3)

<div class="timer"></div> //put this div where you want to show the timer

<input type="button" onClick="fireAJAX();"> // firing ajax call

然后在fireAJAX()函数

function fireAJAX()
{
    var counter = 0;
    var interVal = setInterval(function () {
       $('.timer').html(++counter);     
    }, 1000);

    //Start timer and append the counter to 'timer' div every second

    $.ajax({
        type : "POST",
        url : URL,
        success : function(response){                
             clearInterval(interVal );
             // stop the counter after ajax response
        }
  });
}

因此,每当您调用fireAJAX函数时,计时器将从1开始

答案 2 :(得分:1)

$(document).on('submit', '#formPropiedades', function (event) {
    event.preventDefault();
    var content = {},
    url="http://www.xxxxyzzz.com/xxx/yyy/web/ajax.php"; 
        var setTimer = setInterval(function(){ //start your timer
        var d = new Date();
        document.getElementById("myDivID").innerHTML = d.toLocaleTimeString();//give the id of your div
        },1000);                      
    $("#dialog1").dialog("open");
     var posting = $.post(url, {
            im_core:'saveAllAdds',
            idFeed :<?php echo $_POST['idFeed'] ?>,
            pais:<?php echo $pais1?>
        }).done(function (data) {
            clearInterval(clearInterval); //stop your timer
            if(data==1)
            $(".overlay-bg1").html("Suces....");
            else
            $(".overlay-bg1").html(data);

        }); 
    <?php } ?>  

    });