Nika Nika - 5 months ago 44
Node.js Question

NodeJS setTimeout/setInterval callback as a string

as far as I know, NodeJS does not support callbacks passed by strings in setTimeout/setInterval functions. (e.g setTimeout("myfunc()", 100);)

Is there any implementation or any other solution to make this work? (e.g instead of calling callback, just eval it, etc..)
I'm just trying to load raw webpage which does exactly same thing so NodeJS just throws exceptions on that.


Just replace native setTimeout with your one:

setTimeout = timeoutWrapper(setTimeout);

function timeoutWrapper(origSetTimeout) {
    var win = typeof global !== 'undefined' ? global : window;

    function _setTimeout(fn) {
        var code;
        if(typeof fn === 'string') {
            code = fn
            fn = function wrapEval() {
        arguments[0] = fn;
        origSetTimeout.apply(win, arguments);

    return _setTimeout;

Test it:

setTimeout('console.log(123)', 100);
setTimeout(function(a,b,c) {
        console.log(a, b, c); 
    }, 100, 'aaa', 'bbb', 'ccc');