Update viewport while running script I have a script, which creates multiple objects through a loop. However, the script freezes the viewport until it is done. Instead, I would like every object to be seen in the viewport one by one as it is created. 

In its simplest terms:

import bpy
import random
for i in range(1000):
    XYZcoord = (random.random()*100, random.random()*100, random.random()*100)
    bpy.ops.mesh.primitive_uv_sphere_add(location=XYZcoord)
    # Update the viewport here.


Is there a way to update the viewport after every iteration of the loop to see every newly added object as they are created? Or do I need to use a different method?
The UI (including viewport ) can be updated during the script execution but it is advised against it in the Blender API documentation for these reasons :


  Tools that lock Blender in a loop and redraw are highly discouraged since they conflict with Blenders ability to run multiple operators at once and update different parts of the interface as the tool runs.


so to update the UI during execution you can use wm.redraw_timer() :

import bpy
import random
for i in range(1000):
    XYZcoord = (random.random()*100, random.random()*100, random.random()*100)
    bpy.ops.mesh.primitive_uv_sphere_add(location=XYZcoord)
    # Update the viewport here.
    bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)


a good alternative has been suggested by @Zeffii which is the modal operator triggered by timer