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.

My Reading List -- 3

I love reading books in the predefined order, especially after completing my first two lists ( Reading List 1 , Reading List 2 ). So here is my third list. Kafka On The Shore by Haruki Murakami Murphy’ a Message to Dog Lovers by Ernest Gambier-parry The Prince by Niccolò Machiavelli How to Be a Bawse: A Guide to Conquering Life by Lilly Singh Tao Te Ching by Lao Tzu A Walk To Remember by Nicholas Sparks ReWork: Change the Way You Work Forever by David Heinemeier Hansson, Jason Fried The Gory Story of Genghis Khan: Aka Don’t Mess with the Mongols by Nayanika Mahtani The Art Of Living : The Classical Manual On Virtue, Happiness And Effectiveness by Epictetus A Christmas Carol by Charles Dickens So You Want to Know About Economics by Roopa Pai Wonder by R J Palacio Life is Tremendous: Enthusiasm Makes the Difference by Charlie Jones The Giver by Lois Lowry The Four Agreements: A Practical Guide to Personal Freedom by don Miguel Ruiz Alexander the Great by Jacob Abbot...