Shoutbox

[lib] setTimeout / setInterval - Printable Version

-Shoutbox (https://shoutbox.menthix.net)
+-- Forum: MsgHelp Archive (/forumdisplay.php?fid=58)
+--- Forum: Messenger Plus! for Live Messenger (/forumdisplay.php?fid=4)
+---- Forum: Scripting (/forumdisplay.php?fid=39)
+----- Thread: [lib] setTimeout / setInterval (/showthread.php?tid=72577)

[lib] setTimeout / setInterval by the DtTvB on 03-12-2007 at 12:27 PM

This code allows you to set the timer/interval the same way you use in web pages (setTimeout, setInterval, clearTimeout, clearInterval)..

code:
var setTimeout;
var clearTimeout;
var setInterval;
var clearInterval;
var handleTimer;

function OnEvent_Timer( i ) {
    handleTimer ( i );
}

// An annonymous function, so it won't disturb any other global variables.
// for example, the currentTimer variable is not accessible from any other
// functions.
(function() {

    var currentTimer = 0; // The current timer ID.
    var timersData = [];  // Keeps all data about the timers...
   
    handleTimer = function(tid) {
        if (tid.substr(0, 12) == '_dttvb_timer') {
            var itid = (tid.substr(12) - 0); // convert to number.
            if (typeof timersData[itid] != 'undefined') {
                timersData[itid][0]();
                if (timersData[itid][1]) {
                    MsgPlus.AddTimer (tid, timersData[itid][2]);
                }
            }
        }
    };
   
    setTimeout = function(f, t) {
        var tid = ++currentTimer;
        timersData[tid] = [f, 0, t];
        MsgPlus.AddTimer ('_dttvb_timer' + tid, t);
        return tid;
    };
    setInterval = function(f, t) {
        var tid = ++currentTimer;
        timersData[tid] = [f, 1, t];
        MsgPlus.AddTimer ('_dttvb_timer' + tid, t);
        return tid;
    };

    clearTimeout = function(tid) {
        delete timersData[tid];
    };
    clearInterval = function(tid) {
        delete timersData[tid];
    };

})();

for example,

code:
function foo() {
    // do something
}
setTimeout (foo, 200);

Note that setTimeout ("foo()", 200); will not work.
The reference to the function should be passed in the first parameter, not string. Eval is evil.