0

when I call timer.cancel (), the clock stops working. But when calling back to start a new session, I discover that the _u variable in the old session still counts from itself and parallel with new one.

Please help !

startTime(60);   
timer.cancel();# It worked.
timer = null;   
startTime(60);# but when recall. It working with 2 session. (old and new)
//Call timer.cancel() _u variable stop at 40.

//Recall startTime() _u variable counts with 2 session (40) and (60)  


startTime(reset){
          int _u = reset;
          const oneSec = const Duration(seconds: 1);
                  timer = Timer.periodic(
                    oneSec,
                    (Timer timer) => setState(
                    () {
                        if (_u < 1) {
                          timer.cancel();
                          // call my handle
                    } else {
                          _u = _u -1;
                          if(_u <0){
                            timer?.cancel();
                          }
                        }
                      },
                    ),
                  );
2
  • stackoverflow.com/questions/58956814/… Commented Nov 25, 2020 at 10:53
  • It not useful for me. In my case I wanna closed previous session. (timer cancel and _u stop counts down). Commented Nov 25, 2020 at 12:02

1 Answer 1

1

Cancel the timer if it is not null. The code below was tested

void startTime(reset) {
    int _u = reset;
    const oneSec = const Duration(seconds: 1);

    if (timer != null) {
      timer.cancel();
    }

    timer = Timer.periodic(oneSec, (Timer t) {
      if (_u < 1) {
        t.cancel();
        // call my handle
      } else {
        _u = _u - 1;
        print(_u);
        if (_u < 0) {
          t?.cancel();
        }
      }
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.