javascript - SetInterval and clearInterval issues -
i'm having trouble this, code (simplified):
$(document).ready(function() { var theta = 0; carouselnext = function() { theta += 1; } var carouselinterval = window.setinterval(carouselnext, 1000); var spinning = true; $("#stopstart").click.function() { if (spinning) { clearinterval(carouselinterval); spinning = false; } else { carouselinterval = setinterval(carouselnext, carousel_duration); spinning = true; } }
edit: here full version of code
var carousel_duration = 5000; var html = ''; $(document).ready(function(){ $.getjson("/static/js/users.json", function(data){ $.each(data, function(index, student){ html += '<div class="student">'; html += '<h2>' + student.level + ' of month</h2>'; html += '<h4>' + student.firstname + ' ' + student.lastname + '</h4>'; html += '<p>' + student.class + '</p></br>'; html += '</div>'; }); $('.students').html(html); $('.students').cycle({ fx: 'fade', pause: '1', prev: '#prev', next: '#next', speed: '500', timeout: 10000 }); // catch json reading error }).fail( function(d, textstatus, error) { console.error("getjson failed, status: " + textstatus + ", error: "+error) }); $(".my-btn").click(function() { $('<li>').text("click").prependto('.posts'); }); var carousel = document.getelementbyid('carousel'); var navbuttons = document.queryselectorall('#navigation button'); var panelcount = carousel.children.length; var transformprop = modernizr.prefixed('transform'); var theta = 0; $("#next").on('click', function() { theta += ( 360 / panelcount ) * -1; carousel.style[ transformprop ] = 'translatez( -288px ) rotatey(' + theta + 'deg)'; }); carouselnext = function() { theta += ( 360 / panelcount ) * -1; carousel.style[ transformprop ] = 'translatez( -288px ) rotatey(' + theta + 'deg)'; } var carouselinterval = window.setinterval(carouselnext, carousel_duration); var spinning = true; // stop carousel spinning $("#stop-start").click(function() { if (spinning) { clearinterval(carouselinterval); spinning = false; } else { carouselinterval = setinterval(carouselnext, carousel_duration); spinning = true; } }) // clicking on carousel navigation buttons onnavbuttonclick = function( event ) { var increment = parseint( event.target.getattribute('data-increment') ); theta += ( 360 / panelcount ) * increment * -1; carousel.style[ transformprop ] = 'translatez( -288px ) rotatey(' + theta + 'deg)'; }; (var i=0; < 2; i++) { navbuttons[i].addeventlistener( 'click', onnavbuttonclick, false); } });
when load page, theta ticking 1 every second, expected...
when click "stopstart" button, theta stops ticking up, expected...
however, when click "stopstart" again, theta returns nan. don't see why should case. ideas i'm going wrong?
thanks @gillesc helpful comment - #stop-stort inside #navigation caused onnavbuttonclick fired @ same time carouselnext, causing
increment = parseint( event.target.getattribute('data-increment') );
to fail , turning theta become nan.
Comments
Post a Comment