-
-
Save joepie91/2664c85a744e6bd0629c to your computer and use it in GitHub Desktop.
module.exports = function(duration) { | |
return function(){ | |
return new Promise(function(resolve, reject){ | |
setTimeout(function(){ | |
resolve(); | |
}, duration) | |
}); | |
}; | |
}; | |
// Usage: | |
var delayPromise = require("./delay-promise"); | |
doThing() | |
.then(...) | |
.then(delayPromise(5000)) | |
.then(...) |
There's no need for a timeout. It seems that the app.disableHardwareAcceleration()
behaves like an unawaited function call. In my case, setTimeout with 0 delay works.
I believe this means that a disableHardwareAcceleration()
is a queued task with no internal awaitable tasks, thus kind of atomic.
EDIT: has atomic behavior OR finishes so quickly (as parallel native code) that waiting for app.on('ready') always takes a longer time. This is hypothetical as I haven't checked the code. It's possible that the execution time varies depending on your hardware, resulting in the 0-delay to be an insufficient measure.
$ electron .
app.disableHardwareAcceleration()
app.on('ready', () => setTimeout(createWindow))
As I find myself ending up on this very page approx. once a week (copy pasting @PabloCorso version), here's a Node.js specific alternative for my future self 😄
const delay = require("util").promisify(setTimeout)
Hi @berstend - I don't think util.promisify
does what you hoped.
It expects a function whose callback argument is last. setTimeout
's callback method is first, and timeout in milliseconds is 2nd. (The rarely used context arg is 3rd.)
This necessitates a wrapper function, I use something similar to https://gist.github.com/joepie91/2664c85a744e6bd0629c#gistcomment-2555399 :
const delay = ms => new Promise(yea => setTimeout(yea, ms));
delay(1000)
.then(() => console.log('waited 1000 secs'))
Hello future self, here's the TypeScript version for your copy/pasting pleasure:
const delay = (ms: number) => new Promise(_ => setTimeout(_, ms))
and my favorite JS version:
const delay = ms => new Promise(_ => setTimeout(_, ms))
You forget to clear the setTimeout
const delay = async <T>(timeout: number, value?: T) => {
return new Promise((resolve) => {
const timeoutId = setTimeout(() => {
resolve(value);
clearTimeout(timeoutId);
}, timeout);
});
};
@tolotrasmile That shouldn't be necessary, since this is a setTimeout
, not a setInterval
. A setTimeout
only ever fires once, so once you're in the callback, there is nothing to clearTimeout
anymore.
clearTimeout
is basically just for cancelling a setTimeout
that has not yet occurred.
For nodeJS only
import { setTimeout } from "timers/promises";
await setTimeout(3000, value);
A slight variation could be: