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

How to wait (for 2 seconds) after the completion of function?

本文关键字:等待 2秒 何等待 功能      更新时间:2023-09-26

我有一个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秒钟。如何实现这种情况。

将代码包装在setTimeout:中

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

您可以使用setInterval

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

setTimeout为您提供异步等待时间。对于函数。如果你想让一切暂停两秒钟。您可以使用以下琐碎的解决方案:

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

试试这个

调用一个函数,然后设置TimeOut

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()
{
}

有setTimeout函数

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

还可以使用setInterval函数setInterval(函数,毫秒);