我有这个简单的例子。我需要将参数传递给回调函数。在此代码中,当我不传递任何参数时,计时器工作正常,并在指定的时间间隔过后执行回调函数。但是,如果我传递了 x
,该函数将在不等待 5 秒(或指定的任何时间)的情况下执行。您能解释一下如何将参数传递给回调函数吗?
var x=1;
console.log("starting the script");
setTimeout(myFunction(x),5000);
function myFunction(x)
{
console.log("This should appear after 5 seconds");
if (x==1)
console.log("option 1");
else
console.log("option 2");
}
最佳答案
因为您要立即执行该函数。
另一种方法是用函数声明包装它
var x = 1;
console.log("starting the script");
setTimeout(function() {
myFunction(x);
}, 1000);
function myFunction(x) {
console.log("This should appear after 1 second");
if (x == 1)
console.log("option 1");
else
console.log("option 2");
}
关于javascript - 将参数传递给回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49417514/