1

I would like to put a "pause" in my program. Basically, every time I call my wait() function, nothing should happen until I click the canvas.

Drawrectangle(a,b,c,d)
waitforclick()
drawrectangle(e,f,g,h)

The first rectangle will be drawn, and the second one will not be drawn until I click on the canvas. Thank you for any help.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
user2587878
  • 121
  • 3
  • 15

1 Answers1

1

You may be looking at this problem the wrong way. It's probably not the best idea to halt your program since you want execution to happen as quickly as possible. One of the big advantages to JavaScript is that it has an awesome event API baked in to it.

Instead of making your program wait/sleep, try using events:

drawrectangle(a, b, c, d);

Let's make a function that will run when we detect click events:

function customClickEventHandler(event) {
  drawrectangle(e, f, g, h);
}

And finally, bind your new function to the window's 'click' event. You can choose any DOM element, not just the window.

window.addEventListener('click', customOnClickEvent);

Documentation

Events API: https://developer.mozilla.org/en/docs/Web/API/Event

Follow this link to find out more about the 'addEventListener' function: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Update

If you want to add multiple handlers, it's easy:

function eventHandler1(event) {
  // do something...
}

function eventHandler2(event) {
  // do something else...
}

window.addEventHandler('click', eventHandler1);
window.addEventHandler('click', eventHandler2);
Fernando Lujan
  • 650
  • 7
  • 9
  • Ok, but I am going to have an unlimited amount of different function calls, and I want them all to wait for a click on canvas. So I was hoping I could call a wait function after each separate function executes. – user2587878 Mar 21 '15 at 05:42
  • You can create as many handler functions as you want and have them all listen to the window's click, since events bubble. There's no need to wait. – Fernando Lujan Mar 21 '15 at 15:12
  • @user2587878 I updated my answer to include an implementation with many function calls. If you found my post useful please accept the answer – Fernando Lujan Mar 21 '15 at 19:17
  • That means I have to hard code an event listener for every single function in my program? I will have have over 100 event listeners just to pause my program waiting for user interaction? – user2587878 Mar 23 '15 at 17:51
  • @user2587878 no. You can include all the functionality in a single event handler function if you want. – Fernando Lujan Mar 23 '15 at 21:00