11const canvas = document . getElementById ( 'cvs' )
2+ const stopButton = document . getElementById ( 'stopbutton' )
23const ctx = canvas . getContext ( '2d' )
34const CH = ( canvas . height = 300 )
45const CW = ( canvas . width = 600 )
56canvas . style . background = 'black'
67
7-
8-
98const BubbleSort = {
109 i : 0 ,
1110 j : 0 ,
@@ -20,9 +19,9 @@ const BubbleSort = {
2019 ctx . clearRect ( 0 , 0 , CH , CW )
2120 const lineSpacing = 10
2221 ctx . lineWidth = 5
23- for ( let j = 0 ; j < this . seedValue . length ; j ++ ) {
22+ for ( let j = 1 ; j < this . seedValue . length ; j ++ ) {
2423 const y = j * lineSpacing
25- ctx . beginPath ( )
24+ ctx . beginPath ( )
2625 ctx . moveTo ( y , CH )
2726 ctx . lineTo ( y , CH - this . seedValue [ j ] )
2827 ctx . closePath ( )
@@ -38,14 +37,15 @@ const BubbleSort = {
3837 }
3938 } ,
4039 update ( ) {
40+
4141 if ( this . seedValue [ this . j ] > this . seedValue [ this . j + 1 ] ) {
4242 ; [ this . seedValue [ this . j ] , this . seedValue [ this . j + 1 ] ] = [
4343 this . seedValue [ this . j + 1 ] ,
4444 this . seedValue [ this . j ] ,
4545 ]
4646 this . sortedLine = this . seedValue [ this . j + 1 ]
4747 }
48- if ( this . i < this . seedValue . length ) {
48+ if ( this . i < this . seedValue . length || isClick ) {
4949 this . j ++
5050 if ( this . j >= this . seedValue . length - this . i - 1 ) {
5151 this . color = 'red'
@@ -54,7 +54,9 @@ const BubbleSort = {
5454 }
5555 } else {
5656 this . isLoop = false
57+ clearInterval ( )
5758 }
59+
5860 this . draw ( )
5961 } ,
6062 startup ( ) {
@@ -64,18 +66,31 @@ const BubbleSort = {
6466 this . seedValue [ this . i ] = Math . random ( ) * ( CH - 0 + 1 ) + 0
6567 }
6668 this . i = 0
69+
70+ // Hendling Evnets.
6771 } ,
72+ stopLoop ( ) {
73+ clearInterval ( ) ;
74+ } ,
6875}
6976
7077// You could use window.requestAnimationFrame as well. but, for simplicity i'm using setInterval.
71-
78+ let cleaer ;
79+ stopButton . addEventListener ( 'click' , ( ) => {
80+ // p
81+ // clearInterval(cleaer);
82+ } )
7283function render ( ) {
7384 BubbleSort . startup ( )
74- if ( BubbleSort . isLoop ) {
75- setInterval ( ( ) => {
85+ if ( BubbleSort . isLoop ) {
86+
87+ cleaer = setInterval ( ( ) => {
7688 BubbleSort . update ( BubbleSort . seedValue )
89+
7790 } , BubbleSort . loopSpeed )
78- }
91+ } else {
92+ console . log ( "final" ) ;
93+ }
7994}
8095
8196render ( ) // calling the main functions.
0 commit comments