2012-04-23 46 views
2

我在我的代碼中有以下功能。這裏有一個簡化版本:有沒有什麼辦法可以在我的javascript中引入延遲?

$.ajax({ 
    url: $form.attr('action'), 
    dataType: 'json', 
    type: 'POST', 
    data: $form.serializeArray(), 
    success: function (json, textStatus, XMLHttpRequest) { 
    // delay here 
    alert("hello"); 
    } 

有沒有什麼方法可以引入延遲。例如,延遲5秒進入上面的代碼?

請注意,如果可能,我需要將延遲字替換爲可延遲延遲的內容。

+1

簽出setTimeout函數 - https://developer.mozilla.org/zh-CN/DOM/win dow.setTimeout – 2012-04-23 17:37:28

回答

6

可以使用setTimeout()與匿名函數:

setTimeout(function() { /* your code here */ }, 5000); 

這將有5秒的延遲後運行函數中的代碼。

+0

OP對延遲的期望可能是後面的一段代碼。你可能需要在那裏提到它。 – 2012-04-23 17:38:11

+0

是的,它是爲了後面的代碼。我想用一些東西替換//延遲這裏的單詞。 – 2012-04-23 17:42:48

+0

我不遵循......只是把你想要延遲的任何代碼放在'/ *你的代碼在這裏* /'在我的例子中。在你的例子中,這將是'alert(「hello」);'。這不是回答你的問題嗎? – Brad 2012-04-23 18:04:04

3

當然可以。

$.ajax({ 
      url: $form.attr('action'), 
      dataType: 'json', 
      type: 'POST', 
      data: $form.serializeArray(), 
      success: function (json, textStatus, XMLHttpRequest) { 
        // delay here 
        setTimeout(function() { alert("hello"); }, 5000); 
      }); 
+0

但我可以只是做一個空功能的東西?以上只是一個例子,所以我想用某些東西來替換//延遲的單詞。 – 2012-04-23 17:42:18

2

你可以,如果你想延遲警報只是用

success: function (json, textStatus, XMLHttpRequest) { 
        // delay here 
        setTimeout(function(){alert("hello");}, 5000); // 5000 is in milliseconds 
      } 
2

你會使用setTimeout()這是你如何將其引入自己的代碼使用setTimeout方法

$.ajax({ 
    url: $form.attr('action'), 
    dataType: 'json', 
    type: 'POST', 
    data: $form.serializeArray(), 
    success: function (json, textStatus, XMLHttpRequest) { 
    // save 'this' pointer in case you need it in the setTimeout() function 
    // because it will be set to something different in the setTimeout() callback 
    var self = this; 
    setTimeout(function() { 
     // execute whatever code you want here with a 5 second delay 
     alert("hello"); 
    }, 5000) ; 
    } 
相關問題