I am trying to create a rotating fan simulation using JavaScript & Jquery. My output runs fine 1st time, but when I first stop the fan rotation to zero, and start again the counter value starts from last position of setInterval, is there any way to set it to zero, if once I have reduced the fan speed to zero or how can I use static variable(like in Java) where any operation on the variable reflects throughout program? I tried windows.variable, .variable, but result is the same. Please help My JS and jquery code:
var angle = 0;
var movement;
$(".fan-start").click(function(){
$(".counter").html(window.movement);
window.movement = setInterval(fanOps,1);
});
$(".fan-stop").click(function(){
clearInterval(window.movement);
window.movement--;
if(window.movement>=0)
{
$(".counter").html(window.movement);
}
});
function fanOps()
{
if(angle<360)
{
angle ++;
}
else{
angle = 0;
}
$("img").css("transform","rotate("+angle+"deg)");
}
.counter is the class of the counter value. A screenshot is attached of the page..
My fan operation is working absolutely fine, my issue is setting the counter value back at zero from setInterval, when I start again after bringing it to zero once.
You can use requestAnimationFrame, which is more performant than setInterval (It'll also look better) for this, like so:
var globalID; var angle = 0; var speed = 0.1; function repeatOften() { if(angle<360) { angle+=speed; } else{ angle = 0; } console.log(Math.floor(angle)); globalID = requestAnimationFrame(repeatOften); } globalID = requestAnimationFrame(repeatOften); $("#faster").on("click", function() { speed+=0.1; }); $("#stop").on("click", function() { cancelAnimationFrame(globalID); }); $("#start").on("click", function() { globalID = requestAnimationFrame(repeatOften); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="start">start</button> <button id="stop">stop</button> <button id="faster">faster</button>
you need to hold the setInterval
handler and check the movement
value to start and stop the fan
var angle = 0;
var movement;
var handler; // this keeps the setInterval handler
$('.fan-start').click(function () {
// if the fan is working ,it doesn't need to be started again
if (handler === undefined) {
handler = setInterval(fanOps, 1);
window.movement = 0;
}
window.movement++;
$('.counter').html(window.movement);
});
$('.fan-stop').click(function () {
if (!handler) return;
if (window.movement > 0) {
window.movement--;
}
if (window.movement === 0) {
clearInterval(handler);
handler = undefined;
}
$('.counter').html(window.movement);
});
function fanOps() {
if (angle < 360) {
angle += window.movement;
} else {
angle = 0;
}
$('img').css('transform', 'rotate(' + angle + 'deg)');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.