badbyte.blogg.se

Java script sleep
Java script sleep












java script sleep

Hopefully, you'll have noticed that while reading this blog post, your browser hasn't let your computer go to sleep. It doesn't have any features that you don't need and works with very little setup. I am a little concerned about the lack of security on this API given it's potential to keep the machine from sleeping, however due to the limitations of running only on active tabs I suppose its scope for abuse is limited. If we only need to lock the wake state for a short period, we can even use these with a setTimeout like so.Īnd just like that, you've finished implementing wakeLock.

java script sleep

With those two functions set up we can keep our screen awake for as long as we need. At some point we're likely going to want to release the lock and to do that, we call release on our wakelock variable. We've put the code in a try catch loop as navigator.wakeLock could potentially exist in some other state than we're expecting and that would cause errors.Īt this point we have a window which can prevent the screen from sleeping.

java script sleep

We can also wrap a couple of console.log statements around it to ensure that we can see alerts when the state changes. To actually lock the wake state, we need to call request on our the wakeLock object in the navigator. We can do this with the following simple function. To implement wake lock we first need to check if the feature exists in the current browser. when your blog post has finished being read). This prevents background tabs from keeping your device awake but it can also be released manually via code at any point (eg. Wake Lock only works on active tabs/windows, which I'm sure you'll all agree is a good idea. It is unfortunately unsupported in Firefox and Safari but I don't imagine that Firefox will be too far behind on this implementation. The Screen Wake Lock API allows us to stop the device screen from going to sleep without hacky work arounds that are likely to drain the battery of the device (Such as NoSleep.js). We can make the timeout resolve a promise after a specified amount of time has passed, thereby allowing us to continue the execution of the code after the timeout has passed.įirst, let's create a promise that resolves after a timeout is passed.Hands Covered in Dough by Anastasia Shuraeva via thanks to a web API released in chrome 85, this doesn't need to be an issue any more.

java script sleep

Timeouts allow you to run code after a certain amount of time has passed. You can pause the execution of a JavaScript function for a specified amount of time by taking advantage of the timeouts feature of the JavaScript engine and promises.














Java script sleep