I am trying to make a countdown timer using flutter, but the problem is, my timer seemingly does not update, I am unable to understand what could be the issue.
dartPad link to run the code.
Also I would like to know how to run the timer in reverse, that is starting from 0 seconds.
You have an error here
Duration duration = controller.duration;
Duration is always 1 minute, it's not related to the progress. Use this instead to show an increasing timer (starting in 0)
Duration duration = controller.lastElapsedDuration;
And use this to implement the same but in a countdown manner (starting in 1 minute)
Duration duration = controller.duration - controller.lastElapsedDuration;
Related
This question could be rephrased as: How to invoke a function if 2 seconds pass without an event (re)occurring?
I'm playing with SFSpeechRecogniser. While the user is speaking it sends continuous updates (maybe 2-3 per second). I'm trying to detect when the user stops speaking. If I don't receive any updates for (say) 2 seconds, I can assume that the user has paused speaking.
How to implement this in Swift?
I am aware that I could do:
var timer : Timer?
func f() {
on_event = { result, error in
print( "Got event, restarting timer" )
self.timer?.invalidate()
self.timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { _ in
print( "2s inactivity detected" )
self.timer?.invalidate()
NotificationCenter.default.post( name: inactivity_notification, object: nil )
}
}
}
But is it possible to do it without repeatedly creating and destroying the Timer instance (and thus creating a boatload of temporary Timer instances that never get used)?
One way to do it is to:
Record the current time when an event occurs
Set up a recurring timer with a granularity you are comfortable with (for example 0.25 seconds).
When the timer pops, check difference between current time and last event time. If that is greater than 2 seconds, fire your notification.
This is what I'd do if I had to recognize that a person had stopped typing for 2 seconds. Invalidating and creating timers at typing speed would be a lot of churn. You can tune this to your requirements depending on how close to exactly 2 seconds you need to be.
You could also do this by just having a timeSinceLastEvent variable, and set it to 0 when an event occurs. The recurring timer would increment this by the granularity, and check if it has reached 2 seconds and fire the notification if it had. This is cruder than doing the time math since the timer interval isn't guaranteed, but simpler.
Timer's .fireDate property is writable.
So every time a speech event occurs just do timer.fireDate = Date(timeIntervalSinceNow: 2)
I am having a simple game with a player, a moving background and moving walls, kinda like flappy bird. My player is able to collect a powerUp. It is transforming after and put into a special level.
I want this level to run for like 10 seconds and then call a backtransformation.
Currently I am using a timer which just calls the backtransformation after 10 seconds. I am having trouble now when the player pauses the game, the timer is still running.
--> what I found on stackoverflow is that you can't resume a timer, you can just invalidate and restart it. This would miss my target, otherwise the player pauses the game every 9 seconds and can stay in the super Level forever.
Do you guys have any idea how I can solve my problem or like an alternative to use Timers in my code?
I appreciate any help
Edit: Here is how I simply used the timer
// transform and go into super level added here
self.transform()
timer = Timer.scheduledTimer(withTimeInterval:10, repeats: false) {
timer in
self.backtransform()
}
When you start the timer record the current time as a Double using
let start = Date().timeIntervalSinceReferenceDate
var remaining = 10.0
When the user pauses the timer, calculate the amount of time that has passed with:
let elapsed = Date().timeIntervalSinceReferenceDate - start
And the amount of remaining time for your timer:
remaining -= elapsed
If the user resumes the timer, set it to remaining, not 10 seconds.
I'm attempting to play audio from a specific location inside a file while also receiving updates on the playback using the onTimeUpdate event. I examine the currentTime property within the onTimeUpdate handler so that I can provide visual feedback on where we are in the file.
My problem is that when I set currentTime to a known value and then call play(), the first time I get the currentTime property in my onTimeUpdate handler, it will be as I set it. But the next time onTimeUpdate is called, it's actually a smaller value than I originally started playing from, sometimes more than 100 ms smaller!
For example:
player.currentTime = 2.0;
player.play();
Then, outputting player.currentTime from within my onTimeUpdate handler:
2
1.95 // WTF??
2.24
2.56
...
The problem is that this causes my UI widgets that indicate the current location in the track to jump around. I have a clunky workaround that I am implementing, but I'd like to know if there is any known way to stop this from happening, or if I'm just not doing something right.
To my knowledge, it only happens on iPhone. I'm testing with an iPhone 6 and iOS 10.1.1.
Here's a demonstration if you'd like to see this for yourself.
http://codepen.io/brianrak/pen/7db413c4431827fe3318e99ae497cf2a?editors=1010
Thanks in advance!
var second = ("0" + parseInt(player.currentTime % 60)).slice(-2);
var minutes = ("0" + parseInt((player.currentTime / 60) % 60)).slice(-2);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Xcode: Why is my timer count 2 seconds on every tick?
In my app I have a timer that should go from 12:00 to 0:00, but it counts 2 seconds on every tick like this:
11.58
11.56
11.54
11.52 and so on..
this is the code in the start button code:
tid.text=[NSString stringWithFormat:#"%d:%.2d",minuter,sekunder];
timer= [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(tidklick)
userInfo:nil
repeats:YES];
This is the method tidklick:
-(void) tidklick
{
tiden -= 1;
sekunder = tiden % 60;
minuter= (tiden - sekunder) / 60;
tid.text=[NSString stringWithFormat:#"%d:%.2d",minuter,sekunder];
}
This is the code in the beginning..
int tiden=720;
int sekunder;
int minuter;
and also when I hit a certain button, this should happen: i++;
but it seems like i gets added by 2 every time I hit the button....
What is wrong? :S Seems like something with Xcode and not my code?
EDIT: Now I noticed that when I hit the button that should stop the timer in the end(timer invalidate), it counts as normal... It counts one second at a time that is!
Thanks in advance!
For the second part of the question, when you hit your button: Have you made sure that your selector for the button isn't being called twice -- for instance when the button is pressed down and then again when it is lifted up.
When you say you 'hit the button', what is your button hitting code? There are several events that take place on a button "hit" (most notably button down and up events) which if you are not handling properly could increment i multiple times in a single 'hit'.
This could also be the reason the timer is doing down by two instead of one -- when you 'hit' the start button you are launching two timers instead of one, causing one second per timer to be decremented per second.
For better time counting try to use NSDate methods:
[NSDate date] for start value and [NSDate timeIntervalSinceDate:startTime] to get time shift from the start.
Timer firing interval is approximately equals to 1 second.
Okay, I have searched online and even looked in a couple of books for the answer because I can't understand the apple documentation for the NSTimer. I am trying to implement 2 timers on the same view that each have 3 buttons (START - STOP - RESET).
The first timer counts down from 2 minutes and then beeps.
The second timer counts up from 00:00 indefinitely.
I am assuming that all of the code will be written in the methods behind the 3 different buttons but I am completely lost trying to read the apple documentation. Any help would be greatly appreciated.
Basically what you want is an event that fires every 1 second, or possibly at 1/10th second intervals, and you'll update your UI when the timer ticks.
The following will create a timer, and add it to your run loop. Save the timer somewhere so you can kill it when needed.
- (NSTimer*)createTimer {
// create timer on run loop
return [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerTicked:) userInfo:nil repeats:YES];
}
Now write a handler for the timer tick:
- (void)timerTicked:(NSTimer*)timer {
// decrement timer 1 … this is your UI, tick down and redraw
[myStopwatch tickDown];
[myStopwatch.view setNeedsDisplay];
// increment timer 2 … bump time and redraw in UI
…
}
If the user hits a button, you can reset the counts, or start or stop the ticking. To end a timer, send an invalidate message:
- (void)actionStop:(id)sender {
// stop the timer
[myTimer invalidate];
}
Hope this helps you out.
I would follow Jonathan's approach except you should use an NSDate as your reference for updating the UI. Meaning instead of updating the tick based on the NSTimer, when the NSTimer fires, you take the difference between NSDate for now and your reference date.
The reason for this is that the NSTimer has a resolution of 50-100 ms which means your timer can become pretty inaccurate after a few minutes if there's a lot going on to slow down the device. Using NSDate as a reference point will ensure that the only lag between the actual time and the time displayed is in the calculation of that difference and the rendering of the display.