John Abraham
John Abraham

Reputation: 18781

add a delay at the end of a loop in Javascript/jQuery

I would like to add a delay of 5 seconds after likeMe() loop has finished. Once finsh I would like to trigger a click on the log out button of Facebook.

I'm stupid when it comes to javascript symantics; therefore I have no idea on how to trigger any of this? With this in mind where/how would I add this effect after the loops is over:

I've normally use .promise().done() to do the finally steps after a loops but I have no idea how to place this $.delay(5000).promise().done( $('input[value="Log Out"]').click()); within the javascript.

BACKGROUND: creating a installation art piece using arudino, processing and & greasemonkey jQuery.

FULL SCRIPT:

unsafeWindow.likeMe = likeMe;
function likeMe() 
{   

        input = document.getElementsByTagName("input");
        for(i = 0; i < input.length; i++) 
        {
            myID = input[i].getAttribute("data-profileid");
            if(myID != null && myID.indexOf("342584172457437") >= 0)
                input[i].click();
        }
        $.delay(5000).promise().done( $('input[value="Log Out"]').click()); 
        // this is wrong but yeah i have no clue where or how to put it on here.

}


$(window).load(function(){

    var isCtrl = false;
    document.onkeyup=function(e) {
        if(e.which == 17) isCtrl=false;
    }
    document.onkeydown=function(e){
        if(e.which == 17) isCtrl=true;
        if(e.which == 46 && isCtrl == true) {
            likeMe()

            return false;
        }
    }

});

Upvotes: 2

Views: 331

Answers (2)

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

You can use setTimeout like

function likeMe() 
{   

    input = document.getElementsByTagName("input");
    for(i = 0; i < input.length; i++) 
        {
            myID = input[i].getAttribute("data-profileid");
            if(myID != null && myID.indexOf("342584172457437") >= 0)
            input[i].click();
        }

   setTimeout(function() {
        $('input[value="Log Out"]').click();
   }, 5000);

}

or inside the onkeydown like

document.onkeydown=function(e){
        if(e.which == 17) isCtrl=true;
        if(e.which == 46 && isCtrl == true) {
            likeMe();
            setTimeout(function() {
               $('input[value="Log Out"]').click();
            }, 5000); 
            return false;
        }
    }

But not in both at the same time.

Upvotes: 2

jfriend00
jfriend00

Reputation: 707158

Use setTimeout() like this:

setTimeout(function() {
    $('input[value="Log Out"]').click();
}, 5000);

to execute a function in five seconds.

Upvotes: 0

Related Questions