Q:

stopwatch in javascript using new Date object

In script below i try to make some kind of stopwatch:
<html>
  <head>
   <script>
     var t; var time; var timetoRun=180000;// 3 min

     function Timer()
     {
      stoper = (this.startTime+ this.timetoRun)-new Date().getTime();
      x = parseInt(stoper / 1000);
      s = x % 60;
      x = parseInt(x/60);
      m = x % 60;
      if (s<10) s='0'+ s;document.getElementById('txt').innerHTML=m+':'+s; 
      this.t=setTimeout(function(){Timer()},500);
     }

    function myStopFunction(){clearTimeout(t);}
    function init(){this.startTime = new Date().getTime();}
   </script>
  </head>

   <body onload="init()">
     <div id="txt"></div>
     <button onclick="myStopFunction()">Stop time</button>
     <button onclick="Timer()">Start time</button>
   </body>
</html>

The problem is : when i stop time at 2:28 and start it again after 5 sec. value jump at once to 2:23 . What i want to achieve is: stop time at (for example) 2:31 and run it again from 2:31.
Thanks in advance. 

A:

I think this is the solution you are looking for
<html>
  <head>
   <script>
     var t; 
     var time; 
     var timetoRun=180000;// 3 min
     var lastTime = -1;

    function StartTimer() {
        this.startTime = new Date().getTime();
        this.lastTime = lastTime < 0 ? this.timetoRun : this.lastTime;
        this.timetoRun = this.lastTime;
        Timer();
    };

     function Timer() {
      var difference = (this.startTime - new Date().getTime());
      console.log(difference / 1000);
      this.lastTime = this.timetoRun + difference;
      x = parseInt(this.lastTime / 1000);
      s = x % 60;
      x = parseInt(x/60);
      m = x % 60;
      if (s<10) s='0'+ s;

      document.getElementById('txt').innerHTML=m+':'+s; 

      this.t=setTimeout(function(){
        Timer();
        },500);
     }

    function myStopFunction() {
      clearTimeout(t);
    };

   </script>

  </head>

   <body>
     <div id="txt"></div>
     <button onclick="myStopFunction()">Stop time</button>
     <button onclick="StartTimer()">Start time</button>
   </body>
</html>

or you can try it here
http://plnkr.co/edit/ySOGRCvnPILNTinCriCL?p=preview

