tsangaris Posted March 17, 2015 Share Posted March 17, 2015 (edited) I have created a countdown clock that will be counting down from 100 (looping each second). This is the code: <script> $(document).ready(function(){ $("#buttonClick").on('click', function(){ var initialValue = $("#countdown").text(); setInterval(function () { initialValue--; $("#countdown").text(initialValue); }, 1000); }); }); </script> <body> <button id="buttonClick">Click Me</button> <div id="countdown">100</div> </body> When i click the "Click Me" button the number counts down from 100, 99, 98,97.... When try this from a mobile device and while the device is awake, it works just fine. Lets say the counter is on 50 and i press the power button of the mobile device and it sleeps. If i wake the mobile after 40 seconds, i will not see the remaining 10 seconds but something like 40 or 38 seconds. This happens every time and i don't know why. Can someone help? Regards, Christos Edited March 17, 2015 by tsangaris Quote Link to comment https://forums.phpfreaks.com/topic/295319-mobile-going-to-sleep-and-js/ Share on other sites More sharing options...
Psycho Posted March 17, 2015 Share Posted March 17, 2015 Why would you expect a program to continue to run when you put a phone to sleep? That would kind of defeat the purpose of putting a device to sleep, wouldn't it? The solution is to change your logic to be based off a timestamp. That way once the counter starts up again it will know how many seconds have passed. Quote Link to comment https://forums.phpfreaks.com/topic/295319-mobile-going-to-sleep-and-js/#findComment-1508335 Share on other sites More sharing options...
Solution Psycho Posted March 17, 2015 Solution Share Posted March 17, 2015 Here's a quick example <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function(){ var totalSeconds = 100; var timestamp; var endTime; $("#buttonClick").on('click', function(){ timestamp = new Date(); endTime = timestamp.getTime() + (totalSeconds * 1000); var timer = setInterval(function () { timestamp = new Date(); $("#countdown").text(Math.round((endTime - timestamp.getTime()) / 1000)); if(secondsLeft<=0) { clearInterval(timer); } }, 1000); }); }); </script> </head> <body> <button id="buttonClick">Click Me</button> <div id="countdown">100</div> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/295319-mobile-going-to-sleep-and-js/#findComment-1508338 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.