最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - why settimeout not delay the function execution? - Stack Overflow

programmeradmin6浏览0评论
function tryToDownload(url)
{

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

      setTimeout(deletefile(url), 25000); 
}

following is deletfile function

function deletefile(url){

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

    }
    });
}

above is my jQuery and i m calling one function at the end after 25 second,but some how it's not delaying the deletefile(url) function and execute just after.So what should be the problem?

function tryToDownload(url)
{

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

      setTimeout(deletefile(url), 25000); 
}

following is deletfile function

function deletefile(url){

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

    }
    });
}

above is my jQuery and i m calling one function at the end after 25 second,but some how it's not delaying the deletefile(url) function and execute just after.So what should be the problem?

Share Improve this question edited Dec 22, 2012 at 9:56 Sirko 74.1k19 gold badges154 silver badges189 bronze badges asked Dec 22, 2012 at 9:49 BhavikKamaBhavikKama 8,80012 gold badges95 silver badges166 bronze badges 2
  • possible duplicate of Javascript setTimeout – Fraser Commented Dec 22, 2012 at 9:53
  • 1 @Fraser: That's not really a duplicate IMHO. – Matt Commented Dec 22, 2012 at 16:03
Add a ment  | 

2 Answers 2

Reset to default 19

In this line you are calling your function and pass its result to setTimeout().

setTimeout(deletefile(url), 25000);

If you want to delay the execution, add a wrapper function:

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

EDIT

An alternative proposed by @Petah:

setTimeout(deletefile, 25000, url);

All parameters passed to setTimeout() after the delay, will be passed to the function at execution. So in this case, you pass the reference to the function, the delay and then the parameter to the function in that order!

Note that according to MDN this way of passing parameters wont work in IE before IE9.

That's because you are calling the function, and using the return value in the setTimeout call. Wrap it in an anonymous function so that it's called by setTimeout:

function tryToDownload(url) {

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

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

}
发布评论

评论列表(0)

  1. 暂无评论