2017-07-18 68 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);