0

I'm trying to put a 1 second delay using setTimeout(()=>{},1000) in the Pre-request Script for a Postman POST call.

var moment = require('moment');
var tap1TimeStr = pm.environment.get("now");
var tap1TimeMoment = moment(tap1TimeStr,"YYYY-MM-DDTHH:mm:ss");
var expTap2Time = tap1TimeMoment.add(2, 'minutes').format("YYYY-MM-DDTHH:mm:ss");
console.log("Tap 2 timestamp should be: " + expTap2Time);
var timestamp;
var timecheck = false;
while(!timecheck)
{
    setTimeout(() => {},1000);
    timecheck = moment.utc().isSame(expTap2Time);
    console.log("timecheck: " + timecheck);
    timestamp = moment.utc().format("YYYY-MM-DDTHH:mm:ss");
}
console.log("Timestamp is now: " + timestamp);
pm.environment.set("now", timestamp);

But it doesn't seem to work and I can see that the console.log line is being printed far more frequently than 1sec. And the exercise here is to send the "Tap 2" POST exactly 2mins after the first POST (tracked by the 'now' variable). Also, it seems like Postman takes a fair bit of time before it even starts executing this particular script.

Edit: The main requirement here is to send the "Tap 2" POST request exactly 2mins AFTER the "Tap 1" POST request. HOW best to implement that? Espcially if setTimeout() is non-blocking and thus probably can't be used in a loop.

Anyone has any ideas?

Hazel Chua
  • 23
  • 1
  • 5

1 Answers1

0

setTimeout() takes a callback function which is executed after the specified delay so only what happens in the callback function will happen after that delay.

setTimeout(() => {
    console.log("This will be executed after 1 second");
}, 1000);
console.log("This will immediately be executed");

setTimeout() is asynchronous and non-blocking so JavaScript will call set timeout but not wait for 1 second for it to return and instead immediately move on to the next instruction. Only after that 1 second has passed the callback passed to setTimeout() will be scheduled and executed. Have a look at this YouTube video for a good explanation of what's going on.

Mushroomator
  • 6,516
  • 1
  • 10
  • 27
  • The thing is that I've used the setTimeout call in a different part of my Postman testing and it DOES block and perform a delay of 150secs with no callbacks then progress sending the POST command. – Hazel Chua Mar 12 '22 at 03:20