2012-12-22 44 views
10
function tryToDownload(url) 
{ 

     oIFrm = document.getElementById('myIFrm'); 
     oIFrm.src = url; 
     // alert(url); 
     // url=escape(url); 

     setTimeout(deletefile(url), 25000); 
} 

以下是deletfile功能为什么settimeout不会延迟函数执行?

function deletefile(url){ 

$.ajax({ 
    type:'post', 
    url: "<%= addToDoDeleteDownloadFile %>", 
    data:{filename:url}, 
    type : "GET", 
    timeout : 20000, 
    dataType : "text", 
    success : function(data) { 
     alert("success"); 

    } 
    }); 
} 

以上是我的jQuery和IM经过25第二通话在一端的功能,但它的一些如何不延迟DELETEFILE(URL)功能,只需要执行after.So应该是什么问题?

+0

可能重复(http://stackoverflow.com/questions/4128938/javascript-settimeout) – Fraser

+1

@Fraser:这不是真的一个重复的恕我直言。 – Matt

回答

19

在这一行中,您正在调用您的函数并将其结果传递给setTimeout()

setTimeout(deletefile(url), 25000); 

如果要延迟执行,加一个包装函数:

setTimeout(function(){ deletefile(url); }, 25000); 

编辑提出@Petah

一种替代方案:

setTimeout(deletefile, 25000, url); 

所有参数迟到后传给setTimeout(),会的在执行时传递给函数。因此,在这种情况下,您将参考传递给函数,延迟,然后按照该顺序将参数传递给函数!

请注意,根据MDN这种传递参数的方式在IE9之前不会在IE中工作。

+0

@Bhavik Kama:如果你有'foo(deletefile(url))',那么会立即调用'deletefile'并将其返回值传递给'foo',对吧?正如Sirko所说的,'setTimeout'完全一样。 –

+2

或....'setTimeout(deletefile,25000,url)' – Petah

+0

@Petah,将其他参数传递给该函数在Internet Explorer中不起作用 –

3

这是因为您正在调用该函数,并在setTimeout调用中使用返回值。包装在一个匿名函数,以便它是由所谓的setTimeout:

function tryToDownload(url) { 

    oIFrm = document.getElementById('myIFrm'); 
    oIFrm.src = url; 
    // alert(url); 
    // url=escape(url); 

    setTimeout(function() { deletefile(url); }, 25000); 

} 
[Java脚本的setTimeout]的
+0

thnx男人......它的工作 –