Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

JavaScript How to launch functions from JS setInterval?

Gigiux

Coder
Hello,
I am trying to understand the use of the function setInterval by drawing a Pacman that opens and closes its mouth. I understand that I can launch only one function from setInterval, and this function has to be a wrapper that launches other functions. I set a wrapper drawPac that launches draw_grid (draw a grid in the context) and draw_pacman that overlaps a Pacman to the grid.
I also understand that `setInterval`does do not take arguments easily. Thus, the arguments for these functions should be set as global arguments. draw_grid takes the context; the rest is assigned by default within the function itself.
For draw_pacman, I tried to draw the opening and closing of the mouth by setting an aperture variable (mouth) that starts at 0.2 and that is then decreased by a constant value (0.01) according to the variable increaser. increaser is initially set to -1, so that inside draw_pacman the variable mouth will be adjusted to 0.2 * -1 * 0.001 = 0.199. The updated variable is passed to the function opener that checks if mouth equals 0. Since it is not, at the next iteration, the mouth will become 0.198, and so forth. When mouth will equal 0, increaser will be set to 1, starting to increase the value of mouth. When mouth gets the value of 0.2 again, increaser will return to the value of -1, starting to close the mouth.
However, nothing of this work. In fact, not even the grid is drawn.
  • What is the correct syntax to launch functions from setInterval?
  • How should the flux of parameters pass from one function to the next inside setInterval?
Thank you

This is the code I wrote (also attached for convenience):
HTML:
<!doctype html>
<html>
  <head>
    <title>PacMan</title>
    <link rel="stylesheet" href="styles.css">
    <script src="pacman.js"></script>
  </head>
  <body>
    <h1>Animated PacMan</h1>
    <canvas id="grid" width="400" height="400"></canvas>
    <script>
      var context = document.getElementById("grid").getContext("2d");
      var increaser = -1; // increment for mouth angle
      var mouth = 0.2;    // mouth angle
      var dim = 100;      // dimension of head
      var x = context.canvas.width/2;   // x position of head
      var y = context.canvas.height/2;  // y position of head
      var z = 0.8;
      context.strokeStyle = "white";
      context.lineWidth = 1.5;
      setInterval(drawPac, 1000.0/60.0);
    </script>
  </body>
</html>
JavaScript:
function draw_pacman(ctx, x_pos, y_pos, radius, opening) {
  angle = opening*Math.PI;
  ctx.save();
  ctx.fillStyle = "yellow";
  ctx.strokeStyle = "black";
  ctx.lineWidth = 0.5;
  ctx.beginPath();
  ctx.arc(x_pos, y_pos, radius, angle, -angle);
  ctx.lineTo(x_pos, y_pos);
  ctx.fill();
  ctx.stroke();
  ctx.restore();
}
function opener(startAngle, increaser) {
  endAngle += startAngle+(increaser*0.01);
  if (x == 0) {
    increaser=1 ;
  } else if (x == 0.2) {
    increaser=-1 ;
  }
}
function drawPac() {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  draw_grid(context);
  draw_pacman(context, x, y, dim, mouth);
  mouth = opener(mouth);
  update();
}
function draw_grid(ctx, minor, major, stroke, fill) {
  minor = minor || 10;
  major = major || minor * 5;
  stroke = stroke || "#00FF00";
  fill = fill || "#009900";
  ctx.save();
  ctx.strokeStyle = stroke;
  ctx.fillStyle = fill;
  for(var x = 0; x < ctx.canvas.width; x += minor) {
    ctx.beginPath();
    ctx.moveTo(x, 0);
    ctx.lineTo(x, ctx.canvas.height);
    ctx.lineWidth = (x % major == 0) ? 0.5 : 0.25;
    ctx.stroke();
  }
  for(var y = 0; y < ctx.canvas.height; y += minor) {
    ctx.beginPath();
    ctx.moveTo(0, y);
    ctx.lineTo(ctx.canvas.width, y);
    ctx.lineWidth = (y % major == 0) ? 0.5 : 0.25;
    ctx.stroke();
  }
  ctx.restore();
}
function update(x) {
  x = += x;
}
 

Attachments

Last edited by a moderator:
You have setInterval almost correct but it should be draw_pacman in setInterval. setInterval(function() {
}, time in milliseconds)

You can also use "this" inside that function like "this.method()" or "this.variable". Global variables work though. Inside draw_pacman you can refer to variables as their names to pass them to other things. You may use local variables in that function too with "let". Inside functions names are as passed in or if not that then global variables or error if not local variable. You may also use document to distinguish local and global variables and things. As long as it is global, "document.name" should be able to get it. X E.
 
As to why this isn't working, have you not looked at the Console log ? It will list your errors, one by one.
I can't repeat it enough :
  • if your JS isn't working correctly, check the console log
  • if your HTML isn't working correctly, check it with the W3C online validator
 
As to why this isn't working, have you not looked at the Console log ? It will list your errors, one by one.
I can't repeat it enough :
  • if your JS isn't working correctly, check the console log
  • if your HTML isn't working correctly, check it with the W3C online validator
Can I use a W3C as an extension in Visual Studio? And can validate both HTML and JS as separate files? I used Free Online HTML Validator - FreeFormatter.com on the HTML part of my code but I got only this warning "The character encoding was not declared. Proceeding using “windows-1252”.
 
Can I use a W3C as an extension in Visual Studio? And can validate both HTML and JS as separate files? I used Free Online HTML Validator - FreeFormatter.com on the HTML part of my code but I got only this warning "The character encoding was not declared. Proceeding using “windows-1252”.
I don't know, as I do not use Visual Studio for web programming. I would assume Visual Studio code has some checking functionality but not sure.
That validator you used doesn't seem to do anything except for stating the obvious. By all means go to the https://validator.w3.org/ and check your HTML. IIRC it has a LOT of errors and you'll need several fixing iterations.
As for checking your JS, I think there are validators for that but I've never used them, being quite content with the error messages in the Chrome console.

I tried to install 'Live Server' to debug, but it needs Chrome and instead I am using Firefox, so it does not run...
I had not heard of Live Server. It basically looks like an alternative web server with some added nifty features. It does not say it "needs Chrome". I assume you already have a working web server so I don't know why you'd want this. What makes you think it is a tool for debugging ? If you are using Firefox, why not just use the Firefox debugger ?
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom