完成功能后如何等待(2秒)?

时间:2015-07-01 09:09:59

标签: javascript ajax

我有javascript函数执行,执行后我想等待2秒。是否可以在Javascript中使用。

我的问题不同。我希望在函数执行或完成执行后等待,直到函数执行为止。

Javascript功能

function ajax_closeCall(onDone) {
    // alert("Close Call invoked.");
    closeCall_onDone = onDone;
    var closeCallUrl = soapUrl + "?action=closeCall&parentSessionId=" + parentSessionId;
    closeCall_http_request = getNewHttpRequest('text/plain');
    closeCall_http_request.onreadystatechange = callback_ajax_closeCall;
    // http_request.open("POST", soapUrl, true);
    closeCall_http_request.open("GET", closeCallUrl, true);
    closeCall_http_request.send(null);
}


function callback_ajax_closeCall() {
    if (closeCall_http_request.readyState != 4) {
        return;
    }

    if (closeCall_http_request.status == 200) {
        if (closeCall_onDone) {
            closeCall_onDone();
        }
        stopMonitorCallState();
        ajax_getCallState();
    } else {
        // there was a problem with the request,
        // for example the response may be a 404 (Not Found)
        // or 500 (Internal Server Error) response codes
        alert(getLabel("cmmm_error_closecallfailed"));
    }
}

执行上述功能后,等待2秒钟。 如何实现这种情况。

5 个答案:

答案 0 :(得分:3)

将代码包装在setTimeout:

setTimeout(function() {
    // do your thing!
}, 2000);

答案 1 :(得分:0)

setTimeout为您提供异步等待时间。一个功能。 如果你想停止一切两秒钟。您可以使用以下简单的解决方案:

var date = new Date();var i; 
for (i = date.getTime(); i<= date.getTime() + 2000; i = (new Date()).getTime()){/*Do Nothing*/}

答案 2 :(得分:0)

有setTimeout函数

setTimeout(function,milliseconds,param1,param2,...)

你也可以使用setInterval函数 setInterval(function,milliseconds);

答案 3 :(得分:0)

你可以使用setInterval

&#13;
&#13;
setInterval(function(){
  // write down your function that would you want to call after 2 seconds
}, 2000);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

试试这个

调用一个函数然后setTimeOut

function someFunction() //caller
{
    one(); //call function one which will call second function from it
    setTimeout(function()
    { 
         //wait for 2 secs, do nothing 
    }, 2000);
}

// two functions after which you want to wait for 2 secs
function one()
{
   two(); //it will call the second function
}

function two()
{
}