I hosted my app in Heroku, and I want to stop the setInterval function in a certain condition. It works fine on my local computer but not in Heroku. In the Heroku, my "updateLine()" function still be called three times after the condition newEndX >= 800is met and the clearInterval(intervalID) is called;
Why the "updateLine()" is still called and why three times? Does Heroku work differently from our local computer?
intervalID = setInterval(function () {
if (newEndX < 800) {
updateLine();
}
if (newEndX >= 800) {
clearInterval(intervalID);
alert("You reached the end of the canvas. Please click 'reset' button to startover.")
console.log("reached the end of the canvas.")
console.log("The final startX is", newStartX);
console.log("The final endX is", newEndX);
}
}, 200);
Update: The problem is probably due to some unknown issues in Heroku or my browser. This code works fine in my classmates' computer and his Heroku page.
No idea what could cause the difference between local machine and Heroku, but maybe setTimeout function is fit better for this use-case and can solve the issue.
setTimeout calls a function once after a delay. But the function can have a check for the condition and setup setTimeout to call itself again if the condition passes or just exit if it fails.
setTimeout call can be used instead of setInterval call in your example like this:
function periodicFunction() {
// do something
// should be called again? -> setTimeout
if (newEndX < 800) {
updateLine();
setTimeout(periodicFunction, 200);
// otherwise just finish the work without calling setTimeout
} else {
alert("You reached the end of the canvas. Please click 'reset' button to startover.")
console.log("reached the end of the canvas.")
console.log("The final startX is", newStartX);
console.log("The final endX is", newEndX);
}
}
// initial call
setTimeout(periodicFunction, 200);
setInterval is a javascript function which form queue for requests. It not stops even if error occurs until it get clearInterval. This is due to the internal timer of browser and delay in requests that setInterval has in queue.
If delay increases then setInterval will not stop and call the function again and again.