Sleep and wait functions in C#, JavaScript and Python
Practical examples for creating delays in C#, JavaScript and Python, including sleep, delay and async wait patterns.
Sometimes code has to wait: to avoid hammering a service, to leave a gap between retries, to let an operation finish. Here is how it is done in three languages.
The difference is not only syntax but behaviour: in C# the wait blocks the current thread, which can do nothing else meanwhile. The JavaScript equivalent is promise-based and does not block the browser — the page stays responsive. Python's sleep blocks the current flow as well.
Things to watch
- Units differ: C# and JavaScript take milliseconds, Python takes seconds. Passing the same number to all three is off by a factor of a thousand.
- Never block the main thread in an application with a user interface — it looks frozen.
- For retries, an increasing delay (exponential backoff) is usually better than a fixed wait.
Thread.Sleep(x); // The x value here is in milliseconds.const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
await sleep(x); // The x value here is in milliseconds. import time
time.sleep(x) // The x value here is in seconds.
Short guide
When to use it
Sleep functions help with retry intervals, demos, timed flows and short waits. In applications with a user interface, the key is making sure the wait does not freeze the app.
What to watch
- Do not mix seconds and milliseconds.
- Avoid waits that block the UI thread.
- For API retries, consider increasing wait times instead of a fixed delay.
Common mistake
Using sleep to hide a synchronization problem is common. When possible, wait for an event, callback or promise instead of guessing a duration.
Where this example helps
Small helper snippets like this save time in web applications, mobile app backends, admin panels and API projects. The important part is not copying the example blindly, but adapting it to your data format, security needs and performance expectations.