Memoirs of a Programmer


Javascript : A Better setTimeout

Ever wish you could just simply give a function a line of code (that's always the same) and that function instantly comes back after a specified duration, INCLUDING the original arguments you passed in? Up until now, I didn't have a real quick way of doing this. You would have to use setTimeout and a bit of other ugly tactics to make this happen.

Not today. Instead, use a simple workaround that takes in the function's arguments and creates a setTimeout callback. Here's the line of code you would include in your functions :
 
// Include it like this :

function someFunction(string)
{
detach(arguments, 600);
//600 is the milliseconds duration until the function call is processed


alert("someFunction : " + string);
}

//And then just run your code :

someFunction("Hello world");

// and after 600 milliseconds, the alert window will come up from someFunction :
// 'someFunction : Hello world'

... and voila, we've got a simple way of detaching the function call from the main process!

Here is the method to make this happen :

function detach(_arguments, duration)
{
if(typeof(duration) == "undefined")
duration = 0;

if(_arguments[_arguments.length-1] != "detached")
{
var argument_string = "setTimeout(function(){_arguments.callee(";

for(var i = 0; i < _arguments.length; i++)
{
argument_string += "_arguments[" + i + "], ";
}

argument_string += "'detached')}, " + duration + ");";

eval(argument_string);

ignore.fail();
}
}


Use this function in areas where you don't want a function process to halt the user (So they can visit other parts of the web site). Also useful in SyJAX requests, where the transaction with the server may take a while.

Also, notice that I call a non-existant object method('ignore.fail') so that I can fail out the current main process. If anyone knows a better way to break the entire function process trail, please let me know.

2 Responses to “Javascript : A Better setTimeout”

  1. # Blogger Brett

    To test this technique out, I have built a test script located here  

  2. # Blogger doyle

    This is the way I do this. I just have a call back to the time out. I'm not sure why the detach is better

    var m = 50;
    function fadeMe(){
    setTimeout("foo()",25);
    }
    function foo(){
    var foolink = document.getElementById('foo-link');
    foolink.setAttribute('font-size' , foolink.getAttribute('font-size') - 1);
    if(m != 0){
    fadeMe();
    m--;
    }
    }  

Post a Comment