Jump to content

Mobile going to sleep and JS


tsangaris

Recommended Posts

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




			
		
Link to comment
https://forums.phpfreaks.com/topic/295319-mobile-going-to-sleep-and-js/
Share on other sites

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.

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>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.