Nika Nika - 23 days ago 7
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.

Answer

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() {
                eval(code);
            };
        }
        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');