简体   繁体   English

setTimeOut执行带参数的函数

[英]setTimeOut execute function with parameter

I saw this question , and I'm wondering what is the problem with this? 我看到了这个问题 ,我想知道这有什么问题?

var id = 12;
setTimeout( showGrid ( 'i want to pass variable ' + id + ' here' ), 5000 );

I read the question I'm interested in what the code above is not a good solution. 我读到了我感兴趣的问题,上面的代码不是一个好的解决方案。 I've only Chrome installed, I've tried it and it works. 我只安装了Chrome,我已经尝试过了,但它确实有效。 Is there any browser issue with it? 它有任何浏览器问题吗?

Why the anonymous function is better? 为什么匿名功能更好?

You could use a closure: 你可以使用一个闭包:

var id = 12;
setTimeout(function() {
    showGrid('i want to pass variable ' + id + ' here');
}, 5000);

And here's a live demo . 这是一个现场演示

edit(Milo) from the comments: 编辑(Milo)评论:

the setTimeout function expects a callback or a string variable. setTimeout函数需要回调或字符串变量。 You are not passing such thing so your code is invalid. 你没有传递这样的东西,所以你的代码无效。 You are directly invoking the showGrid function which is not how it is supposed to work. 您正在直接调用showGrid函数,而不是它应该如何工作。 The showGrid function should be invoked only 5 seconds later. 应该仅在5秒后调用showGrid函数。

setTimout expects a function as its first argument and a time as its second argument, then optional arguments to pass to the function. setTimout期望一个函数作为它的第一个参数,一个时间作为它的第二个参数,然后传递给函数的可选参数。 So, if you have a function: 所以,如果你有一个功能:

function showGrid( str ) {
    return str;
}

and you have the following setTimeout : 你有以下setTimeout

setTimeout( showGrid( "..." ), 5000 );

then you are calling showGrid and passing the return value to setTimeout , so it ends up like this: 然后你调用showGrid并将返回值传递给setTimeout ,所以它最终会像这样:

// "..." is returned from showGrid( "..." )
setTimeout( "...", 5000 );

and "..." is not a function. "..."不是一种功能。 So there are two ways to get around this, you can make an enclosure (as in Darin's answer), or add the argument after the time. 因此,有两种方法可以解决这个问题,你可以制作一个封闭空间(如在Darin的答案中),或者在时间之后添加参数。

setTimeout( function() {
    showGrid( "..." );
}, 5000 );

// same thing
setTimeout( showGrid, 5000, "..." );

Example: http://jsfiddle.net/fFg57/ 示例: http//jsfiddle.net/fFg57/

var id = 12;
setTimeout( "showGrid ( 'i want to pass variable " + id + " here' )", 5000 );

the first parameter takes a string, much like what you would pass to a eval function. 第一个参数接受一个字符串,就像你传递给eval函数一样。

and notice the Small o in setTimeout 并注意setTimeout的小o

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM