为什么settimeout没有延迟函数执行? [英] why settimeout not delay the function execution?

查看:424
本文介绍了为什么settimeout没有延迟函数执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function tryToDownload(url)
{

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

      setTimeout(deletefile(url), 25000); 
}

以下是deletfile函数

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

    }
    });
}

上面是我的jQuery,我在25秒后调用了一个函数,但有些如何不延迟deletefile(url)函数并执行刚刚执行。那应该是什么问题?

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?

推荐答案

In这一行是你调用你的函数并将其结果传递给 setTimeout()

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

编辑

@Petah提出的替代方案:

An alternative proposed by @Petah:

setTimeout(deletefile, 25000, url);

所有参数传递到 setTimeout()之后延迟,将在执行时传递给函数。所以在这种情况下,你将引用传递给函数,延迟,然后按顺序传递给函数的参数!

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!

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

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

这篇关于为什么settimeout没有延迟函数执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆