Toggle start and stop jQuery
i'm pretty new to this jquery/javascript stuff but i have this jsfiddle example. So far i have it starting on click but it needs to stop on click as well and return to original state (#pause_but开发者_如何学Pythonton1) which needs to toggle. Any help would be appreciated Thanks in advance :)
It is not 100% clear what you're trying to do, but this could help:
var timer;
var imageNumber = 0;
$('#pause_button1').click(function() {
startWorking();
});
$('#pause_button').click(function() {
if (timer) {
clearTimeout(timer);
timer = false;
$('#pause_button').removeClass('pause_button' + imageNumber);
imageNumber = 0;
}
else {
startWorking();
}
});
function startWorking() {
function changeImage(element) {
$('#pause_button').removeClass('pause_button' + imageNumber);
imageNumber++;
if (imageNumber > 6) {
imageNumber = 1;
}
console.log(imageNumber);
element.addClass('pause_button' + imageNumber, 200);
timer = setTimeout(function() {
changeImage(element)
}, 200);
}
changeImage($('#pause_button'));
}
You could use a interval and use the id
it returns to cancel it using clearInterval
: http://jsfiddle.net/AKgZn/32/.
/* need to run this when clicked - need a toggle */
function changeImage(element, imageNumber) {
function do_it() {
imageNumber++;
if (imageNumber > 6) {
imageNumber = 1;
}
console.log(imageNumber);
element.addClass('pause_button' + imageNumber, 200);
element.attr('class', 'pause_button' + imageNumber);
}
return setInterval(do_it, 200); // execute every 200 ms,
// return interval id
}
var intervalid;
$('div').click(function() {
if(intervalid != null) { // interval running, cancel it
clearInterval(intervalid); // clear the interval
intervalid = null;
} else { // start interval
var id = changeImage($('#pause_button'), 0);
intervalid = id;
}
});
Try
//...
var timeoutId = setTimeout(...);
element.data('timeout', timeoutId);
//...
var elem = $('#pause_button');
if(elem.data('timeout')) {
clearTimeout(elem.data('timeout'));
elem.removeData('timeout');
} else {
changeImage($('#pause_button'), 0);
}
精彩评论