Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  82] [ 5]  / answers: 1 / hits: 30343  / 12 Years ago, thu, august 2, 2012, 12:00:00

My Jquery:



function myTimer() {
var sec = 15
var timer = setInterval(function() {
$('#timer').text(sec--);
if (sec == -1) {
clearInterval(timer);
alert('done');
}
} , 1000);

}

$(#knap).click(function() {
myTimer();
});

$(#reset).click(function() {
// set timer to 15 sec again..
});


I want the timer to be reset when clicked on #reset.


More From » jquery

 Answers
8

You need to leave your timer variable in a scope that is available the next time you call the myTimer function so you can clear the existing interval and reset it with a new interval. Try:



var timer;
functionn myTimer() {
var sec = 15
clearInterval(timer);
timer = setInterval(function() {
$('#timer').text(sec--);
if (sec == -1) {
clearInterval(timer);
alert('done');
}
} , 1000);

}

$(#knap).click(function() {
myTimer();
});

$(#reset).click(function() {
myTimer();
});

[#83895] Wednesday, August 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristab

Total Points: 735
Total Questions: 106
Total Answers: 96

Location: Grenada
Member since Sun, Dec 20, 2020
4 Years ago
tristab questions
Sat, Sep 25, 21, 00:00, 3 Years ago
Sun, Jan 31, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Fri, Oct 23, 20, 00:00, 4 Years ago
;