MONEI / Shopify-api-node

Node Shopify connector sponsored by MONEI
https://monei.com/shopify-payment-gateway/
MIT License
940 stars 279 forks source link

[Improvement]: implementation of delay function without setTimeout #586

Closed jeevan-jp closed 1 year ago

jeevan-jp commented 1 year ago

while loop has been used to improve delay function

jeevan-jp commented 1 year ago

fixes #585

lpinca commented 1 year ago

This is very wrong as it blocks the event loop. Run this

console.log(new Date());

const promise = new Promise(function (resolve) {
  const now = new Date().getTime();
  while (new Date().getTime() < now + 5000) {
    /* Do nothing */
  }
  resolve(null);
});

console.log(new Date());
console.log('OK');

and notice how "OK" is printed after 5 seconds. Now run this

console.log(new Date());

const promise = new Promise(function (resolve) {
  setTimeout(resolve, 5000);
});

console.log(new Date());
console.log('OK');

and see how "OK" is printed immediately.

jeevan-jp commented 1 year ago

Yeah, just went through this repo's delay function calls. You are right, blocking main thread would affect further processing by caller function.

I am still wondering whether there is a better implementation, since accuracy is something that's not guaranteed with setTimeout.

Seems there is none.

lpinca commented 1 year ago

I am still wondering whether there is a better implementation, since accuracy is something that's not guaranteed with setTimeout.

It is a very small inaccuracy (few milliseconds at most) so I think it does not matter.

lpinca commented 1 year ago

I'm closing this. Thank you anyway.