What happens to setTimeout when the computer goes to sleep?

Asked
Active3 hr before
Viewed126 times

8 Answers

90%

Since timers in JavaScript are based on CPU ticks, and the CPU is sleeping, then the timer is completely paused and resumed as 'since nothing would have happen'.,Behaviour of JavaScript timers (setTimeout) in several scenarios.,When the thread is paused because our laptop went to sleep: I have seen several things. But most common is total inaccuracy and ignore of the time spent during sleeping.,When the thread is free and the timeout fires: The timer is fired immediately after the timeout. It might have certain imprecision of about 0-5 ms (typical scenario).

Compare current datetime against datetime when the page was loaded, like so:

//Force refresh after x minutes.
var initialTime = new Date();
var checkSessionTimeout = function() {
   var minutes = Math.abs((initialTime - new Date()) / 1000 / 60);
   if (minutes > 20) {
      setInterval(function() {
         location.href = 'Audit.aspx'
      }, 5000)
   }
};
setInterval(checkSessionTimeout, 1000);
load more v
88%

It seems that for some reason setTimeout enqueued functions are not always invoked when the computer either goes to sleep or wakes up from sleep.,I've noticed that sometimes when putting my computer to sleep similar code stops working. this._timeout != null but the function dispatch is never invoked. Thus, the code is deadlocked.,I'd provide an SSCCE, but the nature of the problem makes that a little hard to do. Any suggestions for ways to better diagnose this issue?,Sorry, I meant the actual source code we use in production. It's a bit difficult to create minimal reproducible example since the behaviour seems to only happen in very specific cases. Probably something timing related...?

function enqueue(args) {
   this._queue.push(args)
   if (!this._timeout) {
      this._timeout = setTimeout(this.dispatch, 10)
   }
}
async function dispatch() {
   while (this._queue.length) {
      // ... do work
   }
   this._timeout = null
}
load more v
72%

Unfortunately this way won't be sutibale if you need to awake application but in my case it's perfect because I wan't to do something when you turn on watch and the time is run out.,Or maybe Timeout counts but can't do nothing when time is elapsed? But it's Illogically, because Timeout will implement methods it has if it can counts. It means that system doesn't sleep.,Application can fall asleep. Time sets once and in the next execution time will be compared.,# You can try requesting CPU to be awaken for the process by using Power API. Don’t forget to release the resource when you are done.

# You can try requesting CPU to be awaken for the process by using Power API. Don’t forget to release the resource when you are done.

tizen.power.request("CPU ", " CPU_AWAKE");
// after completation
tizen.power.release("CPU");
<tizen:privilege name="http://tizen.org/privilege/power" />

(Requesting CPU for long time like an hour seems not an Ideal solution)

load more v
65%

Let's now see how to do the same thing using setInterval():,There is another way to use setTimeout(): you can call it recursively to run the same code repeatedly, instead of using setInterval().,There are a few things to keep in mind when working with setTimeout() and setInterval(). Let's review these now.,Below the previous code, insert a draw() function that will be used to contain our animation code, which includes the timestamp parameter:

let myGreeting = setTimeout(() => {
   alert('Hello, Mr. Universe!');
}, 2000);
load more v
75%

You can use setInterval instead - it keeps on running. If you need a one-shot solution, use clearInterval to delete the timer. setInterval will fire immediately if the computer was asleep while the event should have been fired. I tested this behavior in Chrome, Firefox and Internet Explorer. As an example, have look at http://blaeul.de/de/content/javascript-timer-test and its source.,If no answers are exists it will remove immediately,Note** this option does not delete the question immediately,Since others contribution also matters and security reasons.Your request will be Queued.We will review the question and remove.It may take some days.,I have noticed this in Chrome . Anyone has a idea about what's wrong or a workaround ?

You can use setInterval instead - it keeps on running. If you need a one-shot solution, use clearInterval to delete the timer. setInterval will fire immediately if the computer was asleep while the event should have been fired. I tested this behavior in Chrome, Firefox and Internet Explorer. As an example, have look at http://blaeul.de/de/content/javascript-timer-test and its source.

setInterval
load more v
40%

Nothing at all. Your webpage will work just fine, your buttons will be responsive, and once the 10 second sleep is done, the code next to it will execute. So it's evident that JavaScript does not really block the whole main thread because if it did that, your webpage would have frozen and the buttons would have become non-clickable. ,Consider a webpage in which you have multiple buttons and you run the code above to simulate a sleep for, let's say, 10 seconds. What do you expect will happen?,But what is really happening here?,So we don't really have a full indeterminate situation, just a partial one. And in most cases it's within a margin of a few milliseconds only.

Here's the copy-pasta code which does the job:

/**
 * 
 * @param duration Enter duration in seconds
 */
function sleep(duration) {
   return new Promise(resolve => {
      setTimeout(() => {
         resolve()
      }, duration * 1000)
   })
}
load more v
22%

time_sleep_until() - Make the script sleep until the specified time, If the specified number of seconds is negative, this function will generate a E_WARNING. , If the call was interrupted by a signal, sleep() returns a non-zero value. On Windows, this value will always be 192 (the value of the WAIT_IO_COMPLETION constant within the Windows API). On other platforms, the return value will be the number of seconds left to sleep. ,set_time_limit() - Limits the maximum execution time

05: 31: 23
05: 31: 33
60%

The then() method can be used to execute the required function after the Promise has finished. This simulates a waiting time for a function.,Method 2: Creating a new Promise and using the then() methodA new Promise is created which contains a setTimeout() function. The setTimeout() function is used to execute a function after a specified amount of time. The resolved state of the Promise is used inside the setTimeout() function to finishing it after the timeout.,This method does not block the asynchronous nature of JavaScript and is a preferred method for delaying a function. It is also only supported with the ES6 standard due to the use of Promises.,This type of sleep which uses an infinite loop stall the processing of the rest of the script and may cause warnings from the browser. It is not encouraged to use this type of sleep function for a long duration.

Other "undefined-undefined" queries related to "What happens to setTimeout when the computer goes to sleep?"