Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set time delay for the loop, when everytime its get executed, in Javascript

Tags:

html

I have tried with some code, but it's not working 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>
it's displaying a complete line after 5 seconds, but I need to display a part of line one by one for every 5 seconds.
like image 599
Nagaraj Pujar Avatar asked Feb 06 '26 03:02

Nagaraj Pujar


1 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>
like image 149
Meme Composer Avatar answered Feb 07 '26 23:02

Meme Composer