You could better use setInterval() instead of setTimeout(). With clearInterval() you can stop it from running. The code you made does not work because the for-loop doesn't have scope from itself. You can work around the for loop by using the setInterval().