Skip to main content

JavaScript: Custom setTimeout function to take arguments

Problem:

window.setTimeout method doesn't give easy way to pass object type argument to the timeout method. And it may cause memory leak too. To avoid this, I have written a simple script which does the same thing.

  
var PKTimer = new function()
{
this.timeoutCnt = 1;
}

PKTimer.setTimeout = function(callFn, thisObj, argArr, timeWait)
{
if(argArr === null)
{
return setTimeout(callFn,timeWait);
}
var uniqueId = 'pkt' + PKTimer.timeoutCnt++;
PKTimer[uniqueId] = [callFn, thisObj, argArr];
return setTimeout("PKTimer.timeoutAction('" + uniqueId + "')", timeWait);
}

PKTimer.timeoutAction = function(timeOutId)
{
var callInfo = PKTimer[timeOutId];
if(!callInfo)
{
return;
}
var callFn = callInfo[0];
var thisObj = callInfo[1];
var callArg = callInfo[2];
if(!(callFn instanceof Function))
{
callFn = thisObj[callFn];
}
callFn.apply(thisObj, callArg);
delete PKTimer[timeOutId];
}



function sum(a, b, c)
{
alert("Sum: " + (a + b + c));
}


function MathClass(a, b, c)
{
this.a = a;
this.b = b;
this.c = c;
this.sum = function()
{
alert("MathSum: " + (this.a + this.b + this.c));
}
}

var mathObj = new MathClass(4, 5, 10);
PKTimer.setTimeout(sum, null, [4, 5, 6], 3000);
PKTimer.setTimeout(mathObj.sum, mathObj, [], 6000);



Kovil Pillai P.

Comments

Popular posts from this blog

My Book Shelf - Year 2017

I find it difficult to get this reading order. And I guess it would be still harder to read them without changing the order. I may allow one or two new books to be included in this list, if required. Share book reviews and ratings with Kovil Pillai, and even join a book club on Goodreads.

The Power Game

 Even if you count from the Homo sapiens time, it has been half a million years and from the caveman life to the one who attempts to control the universe, the progress is tremendous. A number of struggles that we have overcome are unimaginable. I am still not convinced whether all these are part of the Divine plan or the Nature adjusts (if at all something is required) itself to any change that takes place in it. As long as we believe in science, we can truly appreciate our power and the things we have achieved. The oldest of the power struggles can be the one between men and women. It is perhaps so subtle that we can’t even call it a power struggle. While we manage to fight against external things, this is something happening in our own race, and we haven’t had an answer yet. A coffee selling 10 times costlier than the price of it in a decade ago may mean the coffee price has been raised. But when you compare it with the price of everything, it is relatively the same. If you look ...