Eightleven Eightleven - 4 months ago 13
jQuery Question

Reset Interval Timer Don't Work! What's wrong?

I wan't to make script timer and reset button. when i click reset then timer will be reseted and running again. i'm new in javascript so it's hard for me.

Here's my html code:

<div class="item html">
<h2>60</h2>
<svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
<g>
<title>Layer 1</title>
<circle id="circle" class="circle_animation" r="69.85699" cy="81" cx="81" stroke-width="8" stroke="#6fdb6f" fill="none"/>
</g>
</svg>
<button type="butoton" id="previous">
Reset
</button>


Here's my JS Code:

var time = 1;
var initialOffset = '440';
var i = 59;
var interval;

var timer = function() {
var interval = setInterval(function() {
$('h2').text(i);
if (i == time) {
clearInterval(interval);
return;
}

i--;
}, 1000);
};


$('#previous').click(function(){
//go back to previous slide and reset time
clearInterval(interval);
timer()
});


Here's my full code: JSFIDDLE

Answer

As you have defined interval outside of the function, you dont need to create new var interval in the function. Just remove the var inside timer function. Check Fiddle

var timer = function() { 
    interval = setInterval(function() {
        $('h2').text(i);
        if (i == time) {    
      clearInterval(interval);
            return;
    }

    i--;  
}, 1000);
};

Also if you would like timer to start from 60 again you should define new time to i. Because inside the timer function you are decreamenting value of i

$(document).ready(function() {
    timer()
});

$('#previous').click(function(){
    //go back to previous slide and reset time
   i=59
   clearInterval(interval);
   timer()
});