Rectangle 27 2

I have the same problem :(. But this is very ugly, since I can use countdown outside of the activity what make very hard to predict when I sould stop it. I don't understand why android is doing that.

Countdown timer problem android - Stack Overflow

android timer countdown
Rectangle 27 45

You can do it like this(ARC Enabled):-

@interface ViewController()
{
UILabel *progress;
    NSTimer *timer;
    int currMinute;
    int currSeconds;
}
@end


@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    progress=[[UILabel alloc] initWithFrame:CGRectMake(80, 15, 100, 50)];
    progress.textColor=[UIColor redColor];
    [progress setText:@"Time : 3:00"];
    progress.backgroundColor=[UIColor clearColor];
    [self.view addSubview:progress];
    currMinute=3;
    currSeconds=00;

    // Do any additional setup after loading the view, typically from a nib.
}
-(void)start
{
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];

}
-(void)timerFired
{
if((currMinute>0 || currSeconds>=0) && currMinute>=0)
{
    if(currSeconds==0)
    {
        currMinute-=1;
        currSeconds=59;
    }
    else if(currSeconds>0)
    {
        currSeconds-=1;
    }
    if(currMinute>-1)
    [progress setText:[NSString stringWithFormat:@"%@%d%@%02d",@"Time : ",currMinute,@":",currSeconds]];
}
    else
    {
        [timer invalidate];
    }
}

Thanx Dear @roronoa zorro your Answer is the best solution that i want.

Hi @roronoa-zorro , was wondering how to deal with pausing the timer?

You cannot pause or restart the Timer , you can only invalidate it.The pause & resume can be replicate by using a NSDate variable , store the current NSDate at the time you want to pause(actually invalidate) & restart the timer from the saved NSDate object

Slightly pedantic comment: NSTimer retains its target so this code will cause ViewController not to be deallocated unless its timer has reached zero. There are a bunch of workarounds mostly involving proxy objects and weak references and it doesn't even necessary really matter quite often you have view controllers you know will never be deallocated anyway (such as the root view controller, commonly).

Thanks buddy i want exact right you posted thnks a lot...

iphone - Implementing a Countdown Timer in Objective-c? - Stack Overfl...

iphone objective-c ios nstimer
Rectangle 27 42

I am using the below code to convert from duration in seconds to the format HH:MM:SS.

You can easily adjust this to accept input in minutes but then your output will be in the format of HH:MM:00 since you do not have seconds, e.g.:

String.format("%02d:%02d:%02d", durationMinutes / 60, durationMinutes % 60, 0);

hi can you post solve problem code

Countdown timer in HH:MM:SS format in Android - Stack Overflow

android timer countdowntimer milliseconds
Rectangle 27 15

I know this is old question, but I want to share my way to achieve this. We have method (timeIntervalSinceDate:) to calculate the interval and have fixed amount of seconds to count down. In my case 300 s.

@IBAction func startTimer(sender: UIButton) {
    sender.selected = !sender.selected;
    //if selected fire timer, otherwise stop
    if (sender.selected) {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateTimer"), userInfo: nil, repeats: true);
        self.startDate = NSDate();
    } else {
        self.stopTimer();
    }

}

func stopTimer() {
    self.timer.invalidate();
}

func updateTimer() {
    // Create date from the elapsed time
    var currentDate:NSDate = NSDate();
    var timeInterval:NSTimeInterval = currentDate.timeIntervalSinceDate(self.startDate!);

    //300 seconds count down
    var timeIntervalCountDown = 300 - timeInterval;
    var timerDate:NSDate = NSDate(timeIntervalSince1970: timeIntervalCountDown);

    // Create a date formatter
    var dateFormatter = NSDateFormatter();
    dateFormatter.dateFormat = "mm:ss";
    dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0);

    // Format the elapsed time and set it to the label
    var timeString = dateFormatter.stringFromDate(timerDate);
    self.timerLabel?.text = timeString;
}
- (void)updateTimer
{
    // Create date from the elapsed time
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate 
                                   timeIntervalSinceDate:self.startDate];
    NSLog(@"time interval %f",timeInterval);

    //300 seconds count down
    NSTimeInterval timeIntervalCountDown = 300 - timeInterval;

    NSDate *timerDate = [NSDate 
                         dateWithTimeIntervalSince1970:timeIntervalCountDown];

    // Create a date formatter
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];


    // Format the elapsed time and set it to the label
    NSString *timeString = [dateFormatter stringFromDate:timerDate];
    self.stopWatch.text = timeString;
}

- (void)stopTimer
{
    [self.stopWatchTimer invalidate];
    self.stopWatchTimer = nil;
    [self updateTimer];

}

- (void)startTimer
{

    if (self.stopWatchTimer) {
        [self.stopWatchTimer invalidate];
        self.stopWatchTimer = nil;
    }

    self.startDate = [NSDate date];    

    // Create the stop watch timer that fires every 100 ms
    self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
                                           target:self
                                         selector:@selector(updateTimer)
                                         userInfo:nil
                                          repeats:YES];
}

it is extremely expensive to create a NSDateFormatter each time you pass through updateTimer. Far better to create the NSDateFormatter outside the loop and reuse it. Credits: @siburb

In case anybody is going to copy/paste this verbatim (you know who you are - ), it is extremely expensive to create a NSDateFormatter each time you pass through updateTimer. Far better to create the NSDateFormatter outside the loop and reuse it.

@siburb, fair point, will include your comment in update

iphone - Implementing a Countdown Timer in Objective-c? - Stack Overfl...

iphone objective-c ios nstimer
Rectangle 27 1

Looks like the code to unmake a countdown timer should be:

$("#divtimerholder").countdown('destroy');

the timer resets to 60 seconds after expiration but it doesn't do the countdown afterwards.

jquery - Restart Countdown Timer when expired - Stack Overflow

jquery countdown
Rectangle 27 3

Is there a reason you're doing it by hand ? If you don't mind using a library, moment.js does a very good job at time manipulations. It's lightweight and very easy to use.

If you have to do it by hand because of some limitations, what are they ?

//Creates a moment. Its value is the time of creation
var timer = moment();

//add 60 seconds to the timer
timer.add(60, 's');

//Removes 1 minutes from the timer
timer.subtract(1, 'm');

Thanks for the link, I will check it out. I am doing it by hand because I would like to understand the code better, so I was hoping if there is a way to do it

javascript - Format time to minutes and seconds in countdown/timer - S...

javascript timer countdown countdowntimer
Rectangle 27 3

IBOutlet UILabel* lblTimer;
 NSTimer* gameTimer;
-(void)viewDidLoad 
{
    [super viewDidLoad];
    [self createTimer];
}

- (void)createTimer 
{       
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
     NSRunLoop* runLoop = [NSRunLoop currentRunLoop];

   gameTimer = [[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] retain];
   [[NSRunLoop currentRunLoop] addTimer:gameTimer forMode:NSDefaultRunLoopMode];
   timeCount = 20; 
   [runLoop run];
   [pool release];
}

- (void)timerFired:(NSTimer *)timer 
{
    if(timeCount == 0)
    {
         [self timerExpired];
    } 
    else 
    {
         timeCount--;
        if(timeCount == 0) {
        [timer invalidate];
        [self timerExpired];
    }
 }
   lblTimer.text = [NSString stringWithFormat:@"%02d:%02d",timeCount/60, timeCount % 60];
   self.title = lblTimer.text;
}

Bind the above Label Outlet with Label in View.

NSRunLoop will hang the control if it is directed on the event invoked by action of a particular UIView'control.

[self timerExpired]; sorry what method is this calling?

iphone - Implementing a Countdown Timer in Objective-c? - Stack Overfl...

iphone objective-c ios nstimer
Rectangle 27 12

I finally got back to looking at this and re-wrote the code and this works like a charm.

<span id="countdown" class="timer"></span>
<script>
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
    var days        = Math.floor(seconds/24/60/60);
    var hoursLeft   = Math.floor((seconds) - (days*86400));
    var hours       = Math.floor(hoursLeft/3600);
    var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
    var minutes     = Math.floor(minutesLeft/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds; 
    }
    document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Completed";
    } else {
        seconds--;
    }
}
var countdownTimer = setInterval('timer()', 1000);
</script>

javascript - Javasacript Countdown timer in Days, Hours, Minute, Secon...

javascript php timer countdowntimer
Rectangle 27 1

Android does have a ready-made CountDownTimer

How To Make A Countdown Timer Android Java? - Stack Overflow

java android timer dialog countdown
Rectangle 27 2

You just need to rearrange your countdown function a bit. It will never be zero when it hits your code that checks for a zero value. The code below works.

function countDown() {

self.seconds--;
      self.element.textContent = self.minutes + ' : ' + self.seconds;

if (self.minutes === 0 && self.seconds === 0) {
  self.stop();
  return;    
}

if (self.seconds <= 0) {
  self.seconds = 59;
  self.minutes--;
}
if (self.seconds <= 9) { self.seconds = '0' + self.seconds; }
  }
};

I can only choose one answer, but I gave you an upvote!

javascript - Countdown timer not stopping at 0 - Stack Overflow

javascript timer countdown countdowntimer
Rectangle 27 1

countDown
function countDown(secs, elem) {
    var element = document.getElementById(elem);
    element.innerHTML = "Please wait for "+secs+" minutes";

    var second = 0;
    var timer = setInterval(function(){
        var extraZero = second < 10 ? '0' : '';
        document.getElementById('num').innerHTML = secs + ":" + extraZero + second;

        if (second-- === 0) {
            second = 59;
            if (secs-- === 0){
                clearInterval(timer);
                element.innerHTML = '<h2>Countdown complete!</h2>';
                element.innerHTML += '<a href="#">Click here now</a>';
            }
        }
    }, 1000);
}

Since you are counting down the seconds, it is making more sense to use setInterval instead of setTimeout.

exactly what I needed, so simple and effective, thank you!

S could perhaps explain me how exactly if (second-- === 0) { second = 59; if (secs-- === 0){ part works..? I understand the extraZero part (if second is less than 10 variable extraZero is '0', and if it is bigger it is empty string '') unless I'm getting it wrong. How exactly conditions second-- === 0 and secs-- === 0 work..? In setTimeout I had secs-- which told the function to countDown, how does setInterval "see" it? Thanks once again

@Joe setTimeout only fires once, while setInterval fires again and again in intervals. In the setInterval function, second-- === 0 would compare second with 0 first, then run second-- regardless of the comparison result. I set second to 0 initially, and do second-- in every interval. When it reaching 0, it would be set to 59. Meanwhile, secs-- === 0 would run to see how many minutes are left, and do secs-- regardless of the comparison. Hope that helps!

I see now, If I got it right there are two intervals going down simultaneously and independent, and second-- actually just goes in circles. Very clever, I learned a lot! Thank you!

javascript - Format time to minutes and seconds in countdown/timer - S...

javascript timer countdown countdowntimer
Rectangle 27 10

CountDownTimer that will display the time formatted to hours,minute,days,and seconds.

public class DemotimerActivity extends Activity {
        /** Called when the activity is first created. */
        TextView tv;
        long diff;
        long milliseconds;
        long endTime;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            tv = new TextView(this);
            this.setContentView(tv);
            SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
            formatter.setLenient(false);


            String oldTime = "21.10.2013, 12:00";
            Date oldDate;
            try {
                oldDate = formatter.parse(oldTime);
                 milliseconds = oldDate.getTime();

                //long startTime = System.currentTimeMillis();
                // do your work...
                long endTime=System.currentTimeMillis();

                 diff = endTime-milliseconds;       

                Log.e("day", "miliday"+diff);
                long seconds = (long) (diff / 1000) % 60 ;
                Log.e("secnd", "miliday"+seconds);
                long minutes = (long) ((diff / (1000*60)) % 60);
                Log.e("minute", "miliday"+minutes);
                long hours   = (long) ((diff / (1000*60*60)) % 24);
                Log.e("hour", "miliday"+hours);
                long days = (int)((diff / (1000*60*60*24)) % 365);
                Log.e("days", "miliday"+days);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            Long serverUptimeSeconds = (System.currentTimeMillis() - milliseconds) / 1000;


                String serverUptimeText = String.format("%d days %d hours %d minutes %d seconds",
                serverUptimeSeconds / 86400,
                ( serverUptimeSeconds % 86400) / 3600 ,
                ((serverUptimeSeconds % 86400) % 3600 ) / 60,
                ((serverUptimeSeconds % 86400) % 3600 ) % 60
                );


            Log.v("jjj", "miliday"+serverUptimeText);
            MyCount counter = new MyCount(milliseconds,1000);
            counter.start();


        }


        // countdowntimer is an abstract class, so extend it and fill in methods
        public class MyCount extends CountDownTimer {
            public MyCount(long millisInFuture, long countDownInterval) {
                super(millisInFuture, countDownInterval);
            }

            @Override
            public void onFinish() {
                tv.setText("done!");
            }

            @Override
            public void onTick(long millisUntilFinished) {
                //tv.setText("Left: " + millisUntilFinished / 1000);

                long diff = endTime - millisUntilFinished; 
                Log.e("left", "miliday"+diff);
                long seconds = (long) (diff / 1000) % 60 ;
                //Log.e("secnd", "miliday"+seconds);
                long minutes = (long) ((diff / (1000*60)) % 60);
                //Log.e("minute", "miliday"+minutes);
                long hours   = (long) ((diff / (1000*60*60)) % 24);
                //Log.e("hour", "miliday"+hours);
                int days = (int)((diff / (1000*60*60*24)) % 365);
                Log.v("days", "miliday"+days);


                Long serverUptimeSeconds = 
                        (System.currentTimeMillis() - millisUntilFinished) / 1000;


                    String serverUptimeText = 
                    String.format("%d days %d hours %d minutes %d seconds",
                    serverUptimeSeconds / 86400,
                    ( serverUptimeSeconds % 86400) / 3600 ,
                    ((serverUptimeSeconds % 86400) % 3600 ) / 60,
                    ((serverUptimeSeconds % 86400) % 3600 ) % 60
                    );  

                    Log.v("new its", "miliday"+serverUptimeText);

                 // tv.setText(days +":"+hours+":"+minutes + ":" + seconds);

                    tv.setText(serverUptimeText);
            }
        }
    }

it actually increase time counter not the down counter.

java - Android Countdown Timer to Date - Stack Overflow

java android eclipse android-layout android-intent
Rectangle 27 3

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
    }

    public void onFinish() {
        mTextField.setText("done!");
    }
}.start();

And then you can manually add/reduce your time with every wrong answer.

java - Android Studio Countdown Timer - Stack Overflow

java android timer countdown
Rectangle 27 1

hourint
minuteint
secondint
onCreate()
start_timer
onClick()
@Override
public void onClick(View view) {
    hourint = Integer.valueOf(number_text.getText().toString());

    minuteint = Integer.valueOf(minute_text.getText().toString());

    secondint = Integer.valueOf(second_text.getText().toString());

    Log.i("YourActivity", "Hours: " + hourint);

    Log.i("YourActivity", "Minutes: " + minuteint);

    Log.i("YourActivity", "Seconds: " + secondint);

    totalTimeCountInMilliseconds = ((hourint*60*60) +(minuteint*60) + (secondint)) * 1000;      // time count for 3 minutes = 180 seconds
    timeBlinkInMilliseconds = totalTimeCountInMilliseconds/1000;

    countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) { 

    ...
}

I meant the top part of setActionListener

java - Getting ints from changeable TextViews to use in CountDown Time...

java android xml timer countdowntimer
Rectangle 27 2

I am not sure of your exact question, but I think you want to know how you can write tests first for your countdown timer?

If so start with writing one of the primary tests, say Start, Stop, or Reset. These are your action events and will be the ones you invoke first (most likely). Code these tests first and execute them. They should be red because they can't actually run the countdown timer.

Then add dummy code to one of the functions in your countdown timer. For instance, add the Start() function which starts the countdown timer. Leave the function empty for now. The test should still be red

Now we need to add a way to get the current time remaining. Add a "Remaining" property where we can check the time remaining. Update the test so that it captures this property, starts the timer and then checks the property again to see if it changed. The test should be red still since we have no code to change the property.

Update the start method to kick off your countdown process and update the internals of your countdown timer. Rerun your test now and it should be green since the value is changing.

Now it's time to refactor. Look through your code and clean things up. Simplify where you can and then reexecute your tests. If all is good everything should be green and you can move on to your next test.

c# - How to implement countdown timer class in TDD? - Stack Overflow

c# tdd timer countdown
Rectangle 27 2

I think Thread can be used, but its easier to implement your features using CountdownTimer wrapper class:

static class MyCountdownTimer {

    long mCurrentMilisLeft;
    long mInterval;
    CountdownTimerWrapper mCountdownTimer;

    class CountdownTimerWrapper extends CountDownTimer{
        public CountdownTimerWrapper(long millisInFuture,long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {

        }

        @Override
        public void onTick(long millisUntilFinished) {
            mCurrentMilisLeft = millisUntilFinished;
        }

    }

    public MyCountdownTimer(long millisInFuture, long countDownInterval) {          
        set(millisInFuture,countDownInterval);
    }

    public void pause(){
        mCountdownTimer.cancel();
    }

    public void resume(){
        mCountdownTimer = new CountdownTimerWrapper(mCurrentMilisLeft, mInterval);
        mCountdownTimer.start();
    }

    public void start(){
        mCountdownTimer.start();
    }

    public void set(long millisInFuture, long countDownInterval){
        mInterval = countDownInterval;
        mCurrentMilisLeft = millisInFuture;         
        mCountdownTimer = new CountdownTimerWrapper(millisInFuture, countDownInterval);
    }

}

Android game countdown timer - Stack Overflow

android timer countdown
Rectangle 27 5

Here is an Android built-in CountDownTimer that will display the time formatted to your days, hours, minutes, and seconds all in a TextView:

public class Example extends Activity {
    CountDownTimer mCountDownTimer;
    long mInitialTime = DateUtils.DAY_IN_MILLIS * 2 + 
                        DateUtils.HOUR_IN_MILLIS * 9 +
                        DateUtils.MINUTE_IN_MILLIS * 3 + 
                        DateUtils.SECOND_IN_MILLIS * 42;
    TextView mTextView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextView = (TextView) findViewById(R.id.empty);

        mCountDownTimer = new CountDownTimer(mInitialTime, 1000) {
            StringBuilder time = new StringBuilder();
            @Override
            public void onFinish() {
                mTextView.setText(DateUtils.formatElapsedTime(0));
                //mTextView.setText("Times Up!");
            }

            @Override
            public void onTick(long millisUntilFinished) {
                time.setLength(0);
                 // Use days if appropriate
                if(millisUntilFinished > DateUtils.DAY_IN_MILLIS) {
                    long count = millisUntilFinished / DateUtils.DAY_IN_MILLIS;
                    if(count > 1)
                        time.append(count).append(" days ");
                    else
                        time.append(count).append(" day ");

                    millisUntilFinished %= DateUtils.DAY_IN_MILLIS;
                }

                time.append(DateUtils.formatElapsedTime(Math.round(millisUntilFinished / 1000d)));
                mTextView.setText(time.toString());
            }
        }.start();
    }
}

number of days is +1 always can that be decreased ?

This method is skipping up to 3 seconds every minute on my emulator. Its not doing it on my phone. Is that an emulator issue, or should i expect that to happen on other phones?.

java - Android Countdown Timer to Date - Stack Overflow

java android eclipse android-layout android-intent
Rectangle 27 1

My opinion is to use javascript for the countdown (embedded as well) and to pass your DB data with json, when DB cause disconnection you pass some data to javascript and with a control you proced to the countdown.

Download the following javascript file and put into your web application directory: http://scripts.hashemian.com/js/countdown.js

<script type="text/javascript">
        TargetDate = "12/25/207 12:01 AM";
        BackColor = "red";
        ForeColor = "white";
        CountActive = true;
        CountStepper = -1;
        LeadingZero = true;
        DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
        FinishMessage = "It is here!";
    </script>

javascript - How to make a countdown timer in asp.net web application(...

c# javascript asp.net timer countdown
Rectangle 27 1

i think its better to take a field in table and set total time for question in it and update that field on every 15/30 seconds (as per your required frequency) and on every update substract the value 15/30 second from total time. and do this till the field has value > 0.

for this you can take help of timer (javascript timer) and ajax. to send request to server to update that field.

with ajax i think its better to create a webservice (which will update value of that field) and call it using ajax on basis of javascript timer. well you can also use ajax timer.

Yes, this is probably the best way for the javascript and the server to always know that the other one is running. However, you need to be aware that a user can disable javascript, and a malicious user can send fake requests to the web service.

javascript - How to make a countdown timer in asp.net web application(...

c# javascript asp.net timer countdown
Rectangle 27 1

Calendar targetTime = Calendar.getInstance();
targetTime.set(Calendar.HOUR_OF_DAY, hour);
targetTime.set(Calendar.MINUTE, minute);
new CountDownTimer(targetTime.getTimeInMillis()-System.currentTimeMillis(), 1000) {
    // here comes your code
}

countdowntimer - Android countdown timer to time in future - Stack Ove...

android countdowntimer