user5821139
user5821139

Reputation:

How to delay api calls in fb api

I am making 2 requests using for loop simultaneously when someone clicks on a button. Then I post a message to their profile; say the messages are the following :

var my_array=["Hi i am jason", "I am feeling great today"];

Above is the array and then I update the statuses using the for loop, so first it loops through the first message and then through the second message.

As I am making this request, those 2 messages are updated on their profile at the same time(maybe a delay of some ms). What I want is the delay of 2s between those 2 messages(indirectly I want the delay between the for loop indices).

So when I click on the button the first message should be updated right away and the second one after 2s.

How can I achieve this?

Upvotes: 0

Views: 138

Answers (1)

andyrandy
andyrandy

Reputation: 74004

You can create a delay in JavaScript with setTimeout: https://developer.mozilla.org/de/docs/Web/API/WindowTimers/setTimeout

For example:

window.setTimeout(function() {
    //do your second API call
}, 2000); //2 seconds delay

One way to solve this (untested, but you should get the idea):

var currentMessageId = 0;

function doAPICall() {
    //do API call with my_array[currentMessageId]

    currentMessageId++;
    if (currentMessageId < my_array.length) {
        window.setTimeout(doAPICall, 2000); //2 seconds delay
    } else {
        //done
    }
}

You can also encapsulate the whole code in a function, so you can call it on button click. Or just set the currentMessageId parameter to zero in the else block.

Btw, prefilling the message is not allowed according to the platform policy. The user must write every single message by himself.

Upvotes: 1

Related Questions