Search code examples
javascriptnode.jsv8

SetTimeout issue in Node.js


I've the following code which runs fine under Chrome (V8) but fails inside node:

var id;
id = setTimeout("TimeoutHandler()", 10);
console.log ('SET');

function TimeoutHandler()
{
  clearTimeout(id);
  console.log ('CLEAR');
}

Chrome output:

SET 
CLEAR 

Nodejs output:

SET
timers.js:110
    first._onTimeout();
          ^
TypeError: Property '_onTimeout' of object [object Object] is not a function
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

Any ideas why? Thanks


Solution

  • Unlike in most browsers, setTimeout in node.js does not accept a string parameter. You must pass it a function. For example:

    function TimeoutHandler()
    {
      clearTimeout(id);
      console.log ('CLEAR');
    }
    
    var id;
    id = setTimeout(TimeoutHandler, 10);
    console.log ('SET');