using task object to have a delay function

DRKOSS's icon

hey all - i often find it handy to have a delay option in JS, so i've defined this in my js file, rather than making several task objects:

var Delayer=new Task(delayed);
var delayValue='';
function delayed(){
    new Function(delayValue)();
    delayValue='';
    }
function delayThis(a,b){
    delayValue=a;
    Delayer.schedule(b);
    }

that way, whenever I want to delay something, i can customize what to delay and for how long - like so:

delayThis('post("hi");',100);

works as expected. max console shows hi after 100ms.

What I can't figure out is this:

Say you have a variable globally defined:

var test='hello';

If you use the delayThis function to change the variable and post it immediately, it behaves as expected:

delayThis('post("'+test+'");test="goodbye";post(test);',100);

produces in the console: hello goodbye.

however if i try and retrieve test after this has delayThis has been called - with a function like:

function retrieveTest(){
    post(test);
}

i still see the original value in the console - hello

if the variable has been changed in the task, why doesn't stay changed globally?

thanks!

do.while's icon

no idea . havent tested it . seems like there is scope weirdness happening with evaluation (perhaps variables are copied to its scope , thats why it processes concatenation properly). I would omit string evaluation at all .

DRKOSS's icon

@do...while thanks for lending it some headspace!

do.while's icon

no worries , but it is still puzzling me .

DRKOSS's icon

aha - got it solved.

needs to be:

var Delayer=new Task(delayed);
var delayValue='';
function delayed(){
    eval(delayValue);
    delayValue='';
    }
function delayThis(a,b){
    delayValue=a;
    Delayer.schedule(b);
    }

example:

delayThis('post("hi");',2500);
handy bit of code to delay whatever js you need to

Jay Walker's icon

I couldn't really get that to work, but here's an example of a delayed function using Task():

var testFunction = function(){
post('eat my shorts');    
        };
var tsk = new Task(testFunction, this);
tsk.schedule(1000);