Adding A Delay Without Thread.sleep And A While Loop Doing Nothing


Answer :

Something like the following should give you the delay you need without holding up the game thread:

private final long PERIOD = 1000L; // Adjust to suit timing private long lastTime = System.currentTimeMillis() - PERIOD;  public void onTick() {//Called every "Tick"     long thisTime = System.currentTimeMillis();      if ((thisTime - lastTime) >= PERIOD) {         lastTime = thisTime;          if(variable) { //If my variable is true             boolean = true; //Setting my boolean to true             /**             *Doing a bunch of things.             **/             //I need a delay for about one second here.             boolean = false; //Setting my boolean to false;         }     } } 

long start = new Date().getTime(); while(new Date().getTime() - start < 1000L){} 

is the simplest solution I can think about.

Still, the heap might get polluted with a lot of unreferenced Date objects, which, depending on how often you get to create such a pseudo-delay, might increase the GC overhead.

At the end of the day, you have to know that this is no better solution in terms of processor usage, compared to the Thread.sleep() solution.


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable