why settimeout not delay the function execution?

会有一股神秘感。 提交于 2019-11-30 23:50:30

问题


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?


回答1:


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.




回答2:


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);

}


来源:https://stackoverflow.com/questions/14001795/why-settimeout-not-delay-the-function-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!