[英]Calling function from array using setTimeout in Javascript
I am creating two function name call and call2 and putting this two functions in array x. 我正在创建两个函数名称call和call2并将这两个函数放在数组x中。 In another function called timer i am trying to call this function every 2 seconds.
在另一个称为计时器的函数中,我试图每2秒调用一次此函数。 But its giving error expected an assigment or function call instead show and expression .
但是它给人的错误是期望一个分配或函数调用而不是show和expression 。
And also i dont want this functions to run when i create an array. 而且我也不希望在创建数组时运行此函数。 this my code http://jsbin.com/IMiVadE/2/
这是我的代码http://jsbin.com/IMiVadE/2/
function call(name)
{
console.log("Hello " + name);
}
function call2()
{
console.log("Hello world");
}
var x = [call("Nakib"), call2()];
var i = 0;
function timer(x, i)
{
x[i];
i++;
if(i<x.length)
window.setTimeout(timer(x, i), 2000);
}
timer(x, i);
You have some mistakes in your code: 您的代码中有一些错误:
Here is your code working: http://jsbin.com/IMiVadE/6/edit 这是您的代码正常工作: http : //jsbin.com/IMiVadE/6/edit
sayHello(name) is a function that generates new functions that output a specific "Hello ..." text. sayHello(name)是一个函数,它会生成输出特定“ Hello ...”文本的新函数。
function sayHello(name)
{
return function () {
console.log("Hello " + name);
}
}
function timer(x, i)
{
x[i]();
if (i < x.length - 1) {
setTimeout(function () {
timer(x, i + 1);
}, 2000);
}
}
var x = [sayHello("Nakib"), sayHello("world")];
setTimeout(function () {
timer(x, 0);
}, 2000);
setTimeout
needs a function without parameter. setTimeout
需要一个没有参数的函数。 So you can wrap the recursive call to timer
in an anonymous function to fix that: 因此,您可以将对
timer
的递归调用包装在一个匿名函数中,以解决此问题:
window.setTimeout(function(){timer(x, i)}, 2000);
Also, the first line in your timer function, consisting only of x[i];
另外,定时器函数的第一行仅由
x[i];
, is useless, although it probably isn't the cause of your problem. ,虽然可能不是造成您问题的原因,但却没有用。
The setTimeout
function takes a function as a parameter, you are executing the timer
function before it is passed and since timer
doesn't return anything, undefined
is being passed to the timeout; setTimeout
函数将一个函数作为参数,您要在传递timer
函数之前执行它,并且由于timer
不返回任何内容,因此会将undefined
传递给超时。
window.setTimeout(timer(x, i), 2000); // is the same as...
window.setTimeout(undefined, 2000);
It should be; 它应该是;
window.setTimeout(function() { timer(x, i) }, 2000); // or...
window.setTimeout(timer.bind(this, x, i), 2000);
I'm not sure if this is intentional, but you are doing the same thing with your array; 我不确定这是否是故意的,但是您对数组执行的操作相同;
var x = [call("Nakib"), call2()];
This will execute the functions and their results will be stored in the array. 这将执行函数,其结果将存储在数组中。 Is this what you want?
这是你想要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.