0

I want to write a sleep() function in javascript/processing.js. I.e: a function that interrupts the flow of the program for however many seconds.

  1. It is obvious how to do this with "busy waiting", but this tends to slow down the browser and make things unusable

  2. I know "sleep" is not good javascript. I want this function for didactic purposes (help kids understand their code), not for production use.

  3. Since it is meant do be didactic, an explicit callback is too much of a complication. Calling the function should be as simple as in , say, bash or php -- however, we can use the most arcane things, just as long as they remain hidden inside the sleep function (including processing.js tricks)

  4. I am aware of question What is the JavaScript version of sleep()?, but still hope there is a hack to stop processing.js (or perhaps a real javascript solution, however ill-advised it might be)

  5. This function should work outside a draw() loop -- if it works inside as well, that is a bonus

If it is relevant, this function is meant to be used on Khan Academy

Community
  • 1
  • 1
josinalvo
  • 978
  • 9
  • 21

1 Answers1

0

It is obvious how to do this with "busy waiting", but this tends to slow down the browser and make things unusable

A sleep() function would also cause this behavior, since JavaScript is single-threaded.

Since it is meant do be didactic, an explicit callback is too much of a complication.

You've pretty much answered your own question: there is no way to do a sleep() function in JavaScript without using a callback or busy waiting.

You might consider using Java mode to show sleep(), but it sounds like busy waiting is the way to go.

And in my humble opinion, even if you could find a hack to cause a sleep, that's probably not a great example for kids, since their code would never do that. They're much more likely to try to render too many objects. If you're trying to demonstrate that doing too much inside of the draw() function will be bad, then why not just have them do too much inside the draw() function? Teach them about for loops and then ask them to see what happens when they draw 100 rectangles, or 1000, or 1,000,000!

Kevin Workman
  • 39,413
  • 8
  • 61
  • 94