James Ross
James Ross

Reputation: 75

Multiple Javascript delays in loop

How do I build in the functionality as demonstrated by the comments?

// for(x=0;x<10;x++)
$('a[attr*="unique"]:first').attr('id', 'mysuperid1');
document.getElementById("mysuperid1").click();
// delay

$("span:contains(action)").parent().click();
// delay

$jq("a:contains(action)").attr('id', 'mysuperid2');
document.getElementById("mysuperid2").click();
// delay

$('input[value="action"]').attr('id', "mysuperid3");
document.getElementById("mysuperid3").click();
// delay

// back to the top of loop

(names and select / search terms have been modified)

The problem I think is like the problem found here http://darklaunch.com/2011/05/21/javascript-for-loop-using-settimeout-to-pass-argument But I can't figure out how to extrapolate what is taught on that link to contain multiple delays since I'm not a javascript developer.

This is a bot which will automate some web tasks for me.

Many thanks

Upvotes: 2

Views: 246

Answers (2)

Ma&#235;l Nison
Ma&#235;l Nison

Reputation: 7353

You can't do 'sleep' actions in Javascript.

However, you can use the async node module, also available for browsers, which will give you some nice asynchroneous syntax wrappers, to help you dealing with asynchroneous functions such as setTimeout.

Your code should be similar to :

async.whilst( function ( ) {
    /* condition */
}, function ( whilstCallback ) {
    async.series( [
        function ( seriesCallback ) { /* action 1 */ seriesCallback( ); },
        window.setTimeout.bind( window, 1000 ),
        function ( seriesCallback ) { /* action 2 */ seriesCallback( ); },
        window.setTimeout.bind( window, 1000 ),
        /* ... */
    ], whilstCallback );
} );

Upvotes: 0

o01
o01

Reputation: 5440

Perhaps you could use this approach as a template, and then divide all your tasks into their own functions.

var delay = 1000;

function beginTasks(){
    taskOne();
}

function taskOne(){
    // Do something
    window.setTimeout(function(){
        taskTwo();
    }, delay);
}

function taskTwo(){
    // Do something else
    window.setTimeout(function(){
        beginTasks(); // <-- back to start
    }, delay);
}

Upvotes: 1

Related Questions