p5.js | noLoop() Function

The noLoop() function is used to stop the program after executing the draw() function. The loop() function runs the draw() function again and again. If noLoop() function is used in setup() function then it should be the last line inside the block. If noLoop() function is used then it is not possible to change or access the screen inside event handling functions such as mousePressed() or keyPressed().

Syntax:

noLoop()

Below examples illustrate the noLoop() function in p5.js:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

function setup() {
    
  // Create canvas of given size
  createCanvas(500, 300);
    
  // Set the background color
  background('green');
    
  // Use noLoop() function
  noLoop();
}
  
function draw() {
    
  // Set the stroke color
  stroke('white');
    
  // Set the stroke width
  strokeWeight(4);
    
  // Function to draw the line
  line(50, 50, 450, 250);
    
}

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

let l = 0;
  
function setup() {
    
  // Create canvas of given size
  createCanvas(500, 300);
    
  // Set the background color
  background('green');
  
}
  
function draw() {
    
  // Set the stroke color
  stroke('white');
    
  l = l + 0.5;
  if (l > width) {
    l = 0;
  }
    
  // Function to draw the line
  line(l, 0, l, height);
    
}
  
function mousePressed() {
  noLoop();
}
  
function mouseReleased() {
  loop();
}

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.