[Solved] For Loop Delay

Hello Everyone,

Is it possible to delay a for loop? If so, how?

Thanks.

Well, yes, with things like Thread.sleep, but I feel like delaying a for loop is something that will not be necessary for anything in sponge. What are you trying to do? Knowing what your goal is, we could help you much better.

1 Like

I have a for loop that spawns falling blocks, but I’d like for them to spawn every second, rather than all at once. In the past, I did try to add Thread.sleep(1000); inside the for loop, but it only spawns one of the blocks, then the rest all at once. Below is the for loop:

    for(Object obj: targets){
				
    String MCT = obj.toString();
				
    MobDropperSpawner.spawnMobDropper(MobCreateConfigUtils.getTarget(MCT));
    }

Schedule it to run every second :slight_smile:

1 Like

Thread.sleep() should never be used within the main thread (“sync”) as it will stop ALL processes including generation, movement etc for one second. This will look like major lag to players on the server.

You’ll want to use Tasks instead. You can create a task that will repeat every second in sync, that repeats X number of times.

Task.builder()
    .interval(1, TimeUnit.MINUTE)
    .execute(() -> {
        // Do loop stuff here (eg an iterator)
    })
    .name("SpawnMobDropper")
    .submit(MyPlugin.getInstance());
1 Like

That’s some mighty interesting code, especially in the context of sponge. I’m incredibly curious what exactly is going on here.

1 Like

Thanks you all for your help! @pie_flavor This code is from a plugin I’ll be releasing within a month or so.

Would you mind explaining how the task works? Sorry if it’s a bit unrelated.

https://docs.spongepowered.org/master/en/plugin/scheduler.html

That doc should explain everthing.

If you haven’t already, go take a look at the other docs too. Could save you a lot of time creating forum posts.

Note that in the docs, scheduler.createTaskBuilder() is identical to Task.builder() as the latter just calls the former as a convenience method (these pop up throughout the API).