javascript - What's the difference between setInterval(func) and setInterval(function(){func()}) -


my ex boss had weird bug when used setinterval long delay interval:

setinterval(func, 3000000 /*50 minutes*/); 

node.js crashed.

func can simple function console.log('something').

someone suggested him wrap anonymous function around func, , solved issue.

as know, shouldn't make difference , considered bad practice @ least in browsers' javascript.

is there difference in node.js between

  • setinterval(func, delay)
  • setinterval(function(){func()}, delay)

or bug in node.js?


update:

bug report on github

to address question directly: yes, there difference. not in functionality of setinterval, in scope function have when it's run.

scenario 1:

setinterval(function() {   console.trace(); }, 3000000); 

every 50 minutes, stack trace printed console. in case because function console.trace has been called directly maintain context of console.

scenario 2:

setinterval(console.trace, 3000000); 

this throw error because invoked context of scope executes it, not console. maintain context, can pass bound copy of function:

setinterval(console.trace.bind(console), 3000000); 

it doesn't seem problem boss had can reproduced today. so, others have suggested, may problem garbage collection. however, more inclined believe function boss calling depended on specific context maintained via anonymous function lost when passing unbound function.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -