Could someone explain why the following code behaves correctly for the first few repeats and then speeds up to manic pace? I searched and found that I should clearInterval before setInterval, but it made no difference.
var begin = window.onload = function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
width = canvas.width = 600,
height = canvas.height = 600;
var stripWidth = Math.floor(Math.random() * (50 - 5 + 1) + 5);
for (i = 0; i <= (width / stripWidth); i++) {
context.strokeRect(stripWidth * i, stripWidth * i, width - (2 * i * stripWidth), width - (2 * i * stripWidth));
}
clearInterval(begin);
setInterval(begin, 1000);
};
Could someone explain why the following code behaves correctly for the first few repeats and then speeds up to manic pace? I searched and found that I should clearInterval before setInterval, but it made no difference.
var begin = window.onload = function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
width = canvas.width = 600,
height = canvas.height = 600;
var stripWidth = Math.floor(Math.random() * (50 - 5 + 1) + 5);
for (i = 0; i <= (width / stripWidth); i++) {
context.strokeRect(stripWidth * i, stripWidth * i, width - (2 * i * stripWidth), width - (2 * i * stripWidth));
}
clearInterval(begin);
setInterval(begin, 1000);
};
Share
Improve this question
edited Oct 22, 2020 at 10:25
Mosh Feu
29.4k18 gold badges93 silver badges141 bronze badges
asked May 17, 2015 at 11:38
Robin AndrewsRobin Andrews
3,80412 gold badges55 silver badges128 bronze badges
1 Answer
Reset to default 8You're using setInterval()
/clearInterval()
wrong. setInterval()
returns a timer-reference, this is the one you need to clear:
var timerRef; // place in parent or global scope so it's accessible inside the function
var begin = window.onload = function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
width = canvas.width = 600,
height = canvas.height = 600;
var stripWidth = Math.floor(Math.random()*(50-5+1)+5);
for (i = 0; i<= (width / stripWidth); i++){
context.strokeRect(stripWidth * i, stripWidth *i,
width - (2 * i * stripWidth), width - (2 * i * stripWidth));
}
clearInterval(timerRef); // clear timer if any
timerRef = setInterval(begin, 1000); // store timerRef
};
timerRef
may be undefined
, null
for clearInterval()