DynamicSleep: An AutoHotkey v2 Sleep That Waits Longer on a Busy PC

Ever had a script that works on your PC and fails on someone else’s?

Often the culprit is a fixed Sleep 500. On a fast, quiet machine that’s plenty. On a slow or busy one, the next step fires before the window is ready.

DynamicSleep is a small AutoHotkey v2 function that pauses longer when the computer is busy and shorter when it isn’t. 😊

Video: creating a self-adjusting sleep that adjusts to your computer's load
Watch how it works on YouTube

How DynamicSleep Measures Your PC


Instead of guessing a number, DynamicSleep times a fixed chunk of work. Then it sleeps for as long as that work took.

  • Step 1: it starts Windows’ high-resolution timer (QueryPerformanceCounter)
  • Step 2: it runs a loop of 10 million steps
  • Step 3: it reads the timer again and sleeps for the time the loop took

A busy computer runs the loop slower, so the pause gets longer automatically.

Use It Where You’d Use Sleep


Include the file and call it between steps that need breathing room:

#Include DynamicSleep.ahk
Run "notepad.exe"
DynamicSleep()         ; pause based on how busy the PC is
Send "Hello"

It also works as a callback, so you can hand it to SetTimer or a button event.

Know What You’re Trading


On my PC one call pauses about one second in total: half for the measuring loop, half for the sleep.

Good fit: scripts you hand to other people, where you can’t know how fast their computer is.
Not a fit: exact timing, or tight loops. The measuring loop keeps one CPU core busy while it runs.

Want a shorter or longer pause? Change the 10,000,000 in the loop. It’s one line.

What’s in the Download


  • DynamicSleep.ahk: the function, about 20 lines with comments on every step
Requirements: Windows and AutoHotkey v2. No other libraries.

Get DynamicSleep


DynamicSleep is $3.00. Pick the price option that suits you. The higher ones help fund more videos and scripts.

A fixed Sleep is a guess. This one at least checks first. ⚡

Joe

Comments are closed.