Pause JavaScript execution depending on timespan between two lines

Let's assume that you want to sleep the JavaScript execution if the timespan between two lines is minor to a certain value.

Example:

javascript
// Setting minimum execution time to 1 second
let min_exec = 1000;

// Getting the starting timestamp
let start = Date.now();

// The program starts to perform a long task. I'll simulate it by
// implementing a for loop between 10^5 <= n < 10^10 
let random = 10**5 + Math.floor((10**10 - 10**5) * Math.random());

// Simulating the task
for(let i = 0, res = 0; i < random; i ++){
    
    res = res + i;
    
}

// Getting the ending timestamp
let end = Date.now();

// Difference between end and start
let timespan = end - start;

// Wait if the difference is minor to a certain value
if(timespan < min_exec){
    
    await new Promise(r => setTimeout(r, min_exec - timespan));
    
}

// At this point, the execution
// will be greater than 1 second
// ...
console.log(Date.now() - start); // Greater than 1000

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.