Skip to content

Instantly share code, notes, and snippets.

@lmuntaner
Created March 26, 2022 06:42
Show Gist options
  • Save lmuntaner/da9291de5e88ff734b9b102ef4d4c623 to your computer and use it in GitHub Desktop.
Save lmuntaner/da9291de5e88ff734b9b102ef4d4c623 to your computer and use it in GitHub Desktop.
Timeout does not guarantee time to executoin
// Select all, copy-paste it in the console and try it out.
const expectedMilliseconds = 1000;
const startTime = new Date();
const logOne = () => console.log(1);
const logTwo = () => {
// This should be close to 0
console.log("Diff:", (new Date() - startTime) - expectedMilliseconds);
console.log(2);
}
const logThree = () => console.log(3);
logOne();
setTimeout(logTwo, expectedMilliseconds);
logThree();
// Below this line you should see the console.logs
// -----------------------------------------------
// Select all, copy-paste it in the console and try it out.
const expectedMilliseconds = 1000;
const startTime = new Date();
const logOne = () => console.log(1);
const logTwo = () => {
// This should be close to 0/
console.log("Diff:", (new Date() - startTime) - expectedMilliseconds);
// But is actually much more than 1 second.
console.log(2);
}
const logThree = () => console.log(3);
logOne();
setTimeout(logTwo, expectedMilliseconds);
logThree();
// Let's keep the Stack busy
for (let i = BigInt(0); i < BigInt("40000000"); i++) {
// Some long calculation
let a = i * i + i / BigInt(4);
};
// Below this line you should see the console.logs
// -----------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment