why settimeout not delay the function execution?

后端 未结 2 716
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-11 21:20
function tryToDownload(url)
{

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

      setT         


        
相关标签:
2条回答
  • 2021-01-11 21:49

    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.

    0 讨论(0)
  • 2021-01-11 21:54

    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 讨论(0)
提交回复
热议问题