[Tex/LaTex] the counter in beamer changed with pause

beamercounters

I define a counter in beamer. But when the pause command occurs, the counter will be added automatically. How can I do to make the counter not sensitive to the pause command? The following is the tex codes for test.

\documentclass[serif,envcountsect]{beamer}

\newcounter{DefNum}
\usecounter{DefNum}
\newcommand{\defi}{\noindent\text{Definition \arabic{DefNum}}\refstepcounter{DefNum}}
\setcounter{DefNum}{1}



\begin{document}
\begin{frame}{test}
\defi

\defi


test hello ~\\ \pause
hello test \pause

\begin{itemize}
  \item aa \pause
  \item bb \pause
  \item cc
  \item \defi
\end{itemize}

\defi
\end{frame}
\end{document} 

Best Answer

The reason for the behavior you get, is that with every \pause you actually create a new page in the resulting PDF. That means, with every \pause the compiler loops again over your entire frame. So after the first run the counter is at 4, processing the next \pause with a new frame it will continue with 5.

The answer from samcarter is the elegant solution, the following is a quick-and-dirty workaround:

You just need to reset the counter at the beginning of the frame to the value it was before creating the first frame:

 \setcounter{preFrameDefNum}{\value{DefNum}}
 \begin{frame}{test}
 \setcounter{DefNum}{\value{preFrameDefNum}}

You can automate the first command by:

\usepackage{etoolbox}
\AtBeginEnvironment{frame}{\setcounter{preFrameDefNum}{\value{DefNum}}}

Full MWE

\documentclass[serif,envcountsect]{beamer}

\newcounter{DefNum}
\newcounter{preFrameDefNum}
\usecounter{DefNum}
\newcommand{\defi}{\noindent\text{Definition \arabic{DefNum}}\refstepcounter{DefNum}}
\setcounter{DefNum}{1}

\begin{document}

\setcounter{preFrameDefNum}{\value{DefNum}}
\begin{frame}{test} 
\setcounter{DefNum}{\value{preFrameDefNum}}

\defi

\defi

test hello ~\\ \pause
hello test \pause

\begin{itemize}
  \item aa \pause
  \item bb \pause
  \item cc
  \item \defi
\end{itemize}

\defi
\end{frame}
\end{document}