2017-07-18 51 views
0

说我有以下的javascript文件:在node.js中使用SetInterval REPL?

function logMe() { 
    for(var i=0; i < 4; i++) console.log(i); 
} 

setInterval(logMe(), 2000); 

然后我打开一个node.js的REPL用命令node

我然后加载与评价我的脚本:

eval(fs.readFileSync('myScript.js').toString()) 

我找回了错误:

TypeError: "callback" argument must be a function 
    at exports.setInterval (timers.js:414:11) 
    at eval (eval at <anonymous> (repl:1:68), <anonymous>:5:1) 
    at repl:1:1 
    at sigintHandlersWrap (vm.js:22:35) 
    at sigintHandlersWrap (vm.js:96:12) 
    at ContextifyScript.Script.runInThisContext (vm.js:21:12) 
    at REPLServer.defaultEval (repl.js:346:29) 
    at bound (domain.js:280:14) 
    at REPLServer.runBound [as eval] (domain.js:293:12) 
    at REPLServer.<anonymous> (repl.js:545:10) 

是否有潜在的工作在这里,如果我想在节点REPL中使用的setInterval ?

+0

'的setInterval(logMe,2000)',_without_的'()'。 –

+2

和FWIW,你只需要'require('./ myScript')'而不是使用'eval()' –

回答

2

不,你只是一个错字。

setInterval(logMe, 2000); 

您需要将您的函数作为函数传递,而不是调用它。

+1

这不是我所说的打字错误。也许OP不知道他在做什么 – bugwheels94

+1

@ bugwheels94。好的,这不会改变我的答案。这可能是一个错字,也可能是无知。无论哪种方式我的答案解决了它。 – Paul

2

logMe()将exexute功能

,其中在setInterval你需要传递函数

function logMe() { 
    for(var i=0; i < 4; i++) console.log(i); 
} 

setInterval(logMe, 2000); 
       ^no() 

function logMe() { 
 
     for(var i=0; i < 4; i++) console.log(i); 
 
    } 
 
    
 
    setInterval(logMe, 2000);


function logMe() { 
 
    for(var i=0; i < 4; i++) console.log(i); 
 
} 
 

 
setInterval(logMe(), 2000);