I enjoy the process of learning by doing. In this section I will be covering some basic use case examples of setTimeout. The basic idea is not that hard, just call the method, and pass the method that is to be called after a set amount of time as the first argument, followed by the amount of time in milliseconds. The function is then called once the set amount of time passes, and that is basically all there is to it. Of course there is more to it than just that in many different use case examples, but I will be getting getting to all that later in this post.
So to just simple delay the call of a function I just need to pass the function and the amount of time like this.
To put together a basic loop all I need to do is call the setTimeout in the body of the method that I pass to setTimeout resulting in a kind of recursion. In many projects it is necessary to define this kind of function to have a situation in which some kind of state is updated on each frame tick.
So setTimeout may not be the best solution for this kind of situation though compares to alternatives such as requestAnimationFrame. However there are a few situations in which I would want to use setTimeout still, more on that later.
If I want to stop setTimeout from continuing there is clearTiemout as well. To use it I just need to pass the timeoutID returned by setTimeout to clearTimeout.
So one of the few reasons why setTimeout and setInterval are still useful alternatives to that of requestAnimationFrame is that it behaves differently when it comes to inactive windows. For example if I am making some kind of game where I want logic to be called every so often even when the window in which the game is running is not active I can do so with setTimeout, where with requestAnimationFrame the loop would be paused.
When I run this the money value steps at a fairly fast rate as expected, but once I switch tabs it slows down to a rate of about one frame tick per second in chrome 70.x. Although the rate at which setTimeout runs is slowed down, it does still run, unlike with requestAnimationFrame. Still because of this nature I will want to design my code accordingly. As such in this example I should step money at a perSecondRate and find out the about of time that elapses each second.