I am working in phonegap ios application. In my application I'm using increment timer and decrement timer using javascript setTimeout function. When I press the menu button in my iPhone the timer function paused its count. When I reopen its start the counting from end. So anyone help me to solve this problem. How to run phonegap ios application javascript function in background.
Timers run on main thread. So when application goes into background they can not run. What you can do is to save the timer count and time when application goes into background. When application comes into foreground, take the difference of time and and it to you count.
you can get source code as well as demo for timer from this link
use the blow code it implement the timer
var count = 0;
var timer = $.timer(function() {
$('#counter').html(++count);
});
timer.set({ time : 1000, autostart : true });
There are many other options also which you can explore. For example
var Example1 = new (function() {
// Stopwatch element on the page
var $stopwatch;
// Timer speed in milliseconds
var incrementTime = 70;
// Current timer position in milliseconds
var currentTime = 0;
// Start the timer
$(function() {
$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
});
// Output time and increment
function updateTimer() {
var timeString = formatTime(currentTime);
$stopwatch.html(timeString);
currentTime += incrementTime;
}
// Reset timer
this.resetStopwatch = function() {
currentTime = 0;
Example1.Timer.stop().once();
};
});
Hope this helps.!
Related
I'm doing an easy slider with buttons, it works fine, but I'd like to add TimeOut() function to current code, to allow slides to change automatically.
I tried to do that with jQuery but it didn't work.
$('.reviews-slider-button').click(function() {
var i = $(this).index();
$('.reviews-slider-person').hide();
$('.reviews-slider-person-' + (i + 1)).show();
});
I'd like to change automatically slider every 10 seconds, and when I would click on .reviews-slider-button it would reset the timer ( to avoid situation I click to change slide, and timer automatically change to the next one).
I'd be grateful for your advice's.
You can use setInterval to click your button every 10 seconds:
var timer = ''; // Make global variable
function ScrollAuto() {
temp = setInterval(function() {
$('.nextButton').click();
}, 10000)
return timer;
}
And to reset your timer, inside your reset button add:
clearInterval(timer);
Similarly to the answer from Shree, but make it cleaner, but use timeout, not interval, you want the system to change slide every 10 seconds unless you click, in which case you reset the timeout, go to the next slide, and set up the next timeout
Something like this:
var slideMaxDuration = 10000; // in ms
var slideTimer = void 0;
function nextSlide() {
clearInterval(slideTimer);
// ... go to next slide ...
}
function autoContinue() {
nextSlide();
setTimeout(autoContinue, slideMaxDuration);
}
$('.reviews-slider-button').click(autoContinue);
You also need to set up the initial autoContinue when you want the whole thing to start.
I want to show loader that will show the time in seconds while loading the app. Here is the code
HTML
<body>
<div class="app-loader">
<div class="loader-spinner">
<div class="loading-text"></div>
</div>
</div>
<angular-app></angular-app>
</body>
Javascript
(function loader() {
var elAppLoader = document.querySelector("app-loader");
var startTime = new Date();
var counter = setInterval(() => {
var seconds = Math.abs((new Date().getTime() - startTime.getTime()) / 1000);
var elLoadingText = document.querySelector(".loading-text");
elLoadingText.innerHTML = seconds.toFixed(2) + " s";
}, 100);
elAppLoader.addEventListener('app-loaded', function (event) {
clearInterval(counter);
elAppLoader.remove();
});
})();
Now this works fine and shows the no of seconds on the screen after every 100ms but when the angular start loading the counter freezes until the angular gets loaded.
How can I solve this? Is this because JS is single threaded if so is there any way to achieve this?
Yes this is beacause browser is busy parsing angular and all the loaded js.
The way to solve this is to use web worker.
Read more about it here: https://www.w3schools.com/html/html5_webworkers.asp
It has a working timer example which suits your case
OK, this is a bit of a tricky one, and I've got a deadline. So anybody who can solve this riddle in the next six hours (by 7am pacific time) gets $100 sent to them via paypal. If not, you still have my undying gratitude for solving the mystery.
I've got an idangero.us swiper with three slides in it. In each slide is a jquery countdown timer from here: http://github.com/rendro/countdown/
Here's how this thing is supposed to work:
When the page loads, you should see a timer count from 3-1 over 3 seconds. When the countdown is finished, it toggles a couple of things. Then there's supposed to be a five second delay, after which, it should automatically slide to the next slide, and the process should repeat. If you manually swipe to another slide, the process should also start over on that slide. Problem is that the timer count doesn't reset. The amount of time does, but the number doesn't. And the timeout function is kinda sketchy. It seems like it skips a beat sometimes.
Here is a dumbed down live example
And here is the Fiddle
And the script:
$(document).ready(function() {
/* initialize swiper */
var mySwiper = new Swiper('.videos',{
loop:true,
grabCursor: true,
onSlideChangeEnd: function(swiper, direction) {
$(".countdown").data('countdown').update(+(new Date) + 3000).start();
}
})
/* create countdown */
$(function() {
$('.countdown').countdown({
date: +(new Date) + 3000,
render: function(data) {
$(this.el).text(this.leadingZeros(data.sec, 0));
},
/* when countdown ends, do this */
onEnd: function() {
$(this.el).addClass('ended');
$(".swiper-slide-active").addClass("loaded");
/* when video is loaded, start timer, and slide to next video */
setTimeout( function() {
$(".swiper-slide").removeClass('loaded');
mySwiper.swipeNext();
},5000);
}
});
});
});
So
Hello im not sure, but You did tried to use function named setInterval...
timerId = setInterval(function()
{
//
}
and then to reset it:
clearInterval(timerId)
Another thing is that the countdown ist working. Is method render really exist in jQuery countdown?
Try following:
/* create var*/
var counter = +(new Date) + 3000;
/* create countdown */
$(function() {
$('.countdown').countdown({
until: counter
},
$('.countdown').countdown(destroy ? 'destroy' : {until: counter });
Maybe destroying and creating countdown every slide would work.
http://keith-wood.name/countdown.html
The below code (I just gave a snippet of working code) animates a few images based on time. Something like a Flash animation where at certain times images start to move at certain times or frame count. My question is , is there a better way to do this ? I know I can use something other than setInterval . I am calculating the elapsed time and setting off images based on the time interval.
It is the ClassLoadImages.prototype.m_draw which is the issue.
function doGameLoop() {
ctx.clearRect(0,0,600,400);
now = new Date();
totalSeconds = (now - start) / 1000;
last = now;
ctx.fillText("totalSeconds=" +totalSeconds ,10,100);
if (totalSeconds>2 && totalSeconds<6)
{
img2.m_draw(130);
}
if (totalSeconds>4 && totalSeconds<8)
{
img3.m_draw2(230);
}
if (totalSeconds>10){
start = new Date();//start again
}
img.m_draw(30);
// fi++;
}
var img= new ClassLoadImages(30,30);
var img2= new ClassLoadImages(30,30);
var img3= new ClassLoadImages(30,30);
</script>
If you want something like flash movieclips, check out SpriteClip on github. https://github.com/wolthers/SpriteClip.js
In my game I have set the timer to 30000ms (30 secs). When the timer ends the game ends. I want to show the user the timer to give them some idea of how long they have left. How would I do this, I have tried to do it like this:
setTimeout(function() {
$("#message").html('Thank you for playing. </br> You answered </br>' + hit + '/' + attempted + ' correctly. </br> Press "Play" to start again.').fadeIn('slow');
$(".character").fadeIn('slow');
}, 500);
});
}, 30000).show('#timer'); //here I am trying to display the time in the "#timer"
}
I think I am approaching this all wrong can someone give me a point in the right direction?
Fiddle: http://jsfiddle.net/cFKHq/8/
Have a gander at this jsFiddle. You just need to change your timeout to an interval and keep a count of the seconds.
Instead of running the timer by all 30000 at once, run the timer in 1000ms increments. Each time it hits, subtract one from the counter, refresh the page, and if the counter is 0, end the game.
I changed the jsfiddle you posted to show a counter after pushing play button. See http://jsfiddle.net/cFKHq/10/
Inside your function startplay() I added a variable ttime with an initial value of 30 and I added the line $("#timer").text(--ttime); to the setInterval argument function that is called every second.
Look into using delta times. I have found this to be a great way to handle things that need to measure changes in time.
prevTime = curTime;
curTime += new Date();
deltaTime = curTime - prevTime;
This will also allow you to have a "x seconds remaining" counter if you fire off an event every 1 second, or even every 100ms. All depends on how fast you want it to go.
You need to seperate your timer logic from your "game over" logic, as the timer should tick regardless:
var secondsLeft = 30;
var timerElement = $('#timer');
(function timer() {
timerElement.text(secondsLeft);
secondsLeft--;
if (secondsLeft !== 0) {
setTimeout(function () {
timer();
}, 1000);
}
}());
http://jsfiddle.net/cFKHq/14/
Note that in this solution the 30 * 1 second timer countdown and 30 seconds of gameplay are not related or reliant on one another, which may cause some synchronicity issues if the user is on a slow machine.
You can use a global window.duration variable were you set the seconds the game will last, then decrement from that in the "one second" interval:
See working demo
At start of script:
var hit = 0;
var attempted = 0;
var target = $("#target");
window.cont = true;
window.duration = 30; //set your desired game duration in seconds
then on the "one second interval" we decrement the timer and print the timer text:
play = setInterval(function() {
if (window.cont) {
window.cont = false;
scramble();
}
window.duration--;
$('#timer').html(window.duration + ' seconds to go');
}, 1000);
Also display a "finished" text when the game ends, the relevant part follows:
setTimeout(function() {
$("#message").html('Thank you for playing. </br> You answered </br>' + hit + '/' + attempted + ' correctly. </br> Press "Play" to start again.').fadeIn('slow');
$(".character").fadeIn('slow');
$('#timer').html('Finished');
}, 500);
Here is an example: http://jsfiddle.net/RPSMJ/4/
JavaScript
var counter = 30,
timerOutput = document.getElementById('timerOutput');
(function timer() {
timerOutput.innerHTML = counter;
counter -= 1;
if (counter >= 0) {
setTimeout(function () {
timer();
}, 1000);
}
}());
HTML
<div id='timerOutput'></div>