2017-03-02 501 views
0

我需要在運行window.location.href之前添加2秒的睡眠時間。如何在jQuery中設置睡眠時間?

例如:

$.ajax({ 
    url:"price", 
    method:"POST", 
    }).done(function (data) { 
     var origin = window.location.origin; 
     // I need add 2 sec sleep 
     window.location.href = origin + "/flight/ticket/" + data; 
    }).error(function (xhr, opt, error) { 
     $('#trustCaptcha').show(); 
     $('#getTicket').hide(); 
    } 
); 

謝謝。

回答

2

您可以使用setTimeout()方法。

$.ajax({ 
    url: "price", 
    method: "POST", 
}).done(function(data) { 
    var origin = window.location.origin; 
    // I need add 2 sec sleep 
    setTimeout(function() { 
    window.location.href = origin + "/flight/ticket/" + data; 
    }, 2000); 
}).error(function(xhr, opt, error) { 
    $('#trustCaptcha').show(); 
    $('#getTicket').hide(); 
}); 

你可以閱讀更多有關此方法here

+1

謝謝你的幫助:-) – mySun

+0

不客氣。樂於幫助。 – Ionut

1

您可以使用setTimeout()延遲邏輯執行。試試這個:

$.ajax({ 
    url:"price", 
    method:"POST", 
}).done(function (data) { 
    var origin = window.location.origin; 
    setTimeout(function() { 
    window.location.href = origin + "/flight/ticket/" + data; 
    }, 2000); // 2000ms = 2 seconds 
}).error(function (xhr, opt, error) { 
    $('#trustCaptcha').show(); 
    $('#getTicket').hide(); 
}); 
+0

謝謝你的幫助:-) – mySun

+0

沒問題。不要忘記接受幫助 –