How to set time delay for a loop when every time it is executed in Javascript
I tried with some code but it doesn't work fine.
var canvas=document.getElementById('can');
ctx=canvas.getContext('2d');
canvas.width=1200;
canvas.height=750;
for (var x = 100; x <=900; x+=10) {
linedraw(x);
}
function linedraw(n) {
setTimeout(function(){
ctx.moveTo(n,100);
ctx.lineTo(n+20,100);
ctx.stroke();
},1000 * 5);
}
<canvas id="can" style="background-color: gray"></canvas>
+3
source to share
2 answers
Here you go
var canvas=document.getElementById('can');
ctx=canvas.getContext('2d');
canvas.width=1200;
canvas.height=750;
for (var x = 100; x <=900; x+=10) {
linedraw(x);
}
function linedraw(n) {
setTimeout(function(){
ctx.moveTo(n,100);
ctx.lineTo(n+20,100);
ctx.stroke();
},5000/900*n); // change here
}
<canvas id="can" style="background-color: gray"></canvas>
+1
source to share
You need to wrap the timeinterval set inside a set timeout. In the below code, you can change the time interval according to your needs.
JS:
var canvas = $("#myCanvas")[0];
var c = canvas.getContext("2d");
var amount = 0;
var startX = 164;
var startY = 120;
var endX = 1094;
var endY = 120;
setTimeout(function() {
setInterval(function() {
amount += 0.01; // change to alter duration
if (amount > 1) amount = 1;
c.clearRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = "black";
c.lineWidth=1;
c.strokeStyle="#707070";
c.moveTo(startX, startY);
// lerp : a + (b - a) * f
c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
c.stroke();
}, 100);
}, 0);
HTML:
<canvas id="myCanvas" width="1250" height="120"></canvas>
+1
source to share