So, many of you will probably think, why the heck would I want to INCREASE run time on Script Activities or Cloud pages, when there is a time limit on both. This is a very valid point. But, there are times when a wait period can be super helpful as well.

For instance, one use case I hear about frequently is for creating a record in SFDC and then querying it for use (maybe in a Custom Preference center) in a Cloud Page. This cannot be done one after the other, or more often then not, the query will fail.

Another fairly popular use case is if you are running a query or automation and you then want to check the status to verify it is running after initiation whether it is to make sure there was no error, or to see if you can move on to the next part of your script.

Or, if you are looking to start multiple objects and don’t want them all started at the same time, you can put a wait time between them to help reduce the risk of failure.

There are a ton more uses for SSJS wait function as well and it could take me years to list them all. So, instead, I am going to get directly to the function for reference and explain it.

<script runat=server>

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

sleep(1000); //Wait for 1 second

</script>

So basically what the function sleep() does is process through a for loop for over 166 minutes (1e7 = 10,000,000).

The if statement inside of this loop is used to find the inserted value declared in the function call (milliseconds) by subtracting the current time from the start time. Once the number of ‘milliseconds’ passed matches the milliseconds argument you entered, the loop is broken via the break command.

Are there other options for this? Sure there are, this is just the one that I have found to be the most useful to me.

For instance, technically in an automation, you could split your script into multiple parts and utilize the baked in ‘Wait’ interaction as well if you are worried about timeouts or want to reduce code and processing complexity.

Tags: , , , , , , , ,
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mahammed Anfal K
Mahammed Anfal K
1 year ago

Works like a charm in SSJS!

Very helpful because of SSJS NOT supporting the “setTimeout()”

Thank you! 🙂

Abc
Abc
2 months ago

Does it make the cpu working for nothing ?
Is there another way ? What about making the SSJS calling a fake https API and make the timeout time to fake a sleep ?

Or is there an public API that everyone can call that just block the connection for a certain amount of time, and then reply with 200, so it may simulate a sleep ?

Last edited 2 months ago by Abc