Skip to content
Advertisement

Set timeout function not slowing down

I am trying to create a loading screen and have different sets of text show up while it’s loading, but when I increase the rate to 5 secs, the function skips to the last set of loading screen text and doesn’t show the other sets. How can I solve this issue?

JS:

JavaScript

Advertisement

Answer

There are two issues in your code.

  1. We don’t see where you are waiting for the dom loaded event, since we can’t verify we need to ensure that you have guarded your dom accesses by the DOMContentLoaded event. If you missed this step then the updates would not happen.
  2. The ordering of your setTimeouts based on reading it seems like you want one after another of these messages to display. As written in the question these would all effectivly run at the same time.

The best way to address this issue is use JS promises if available in your target browser (probably works unless you need IE compatibility and cannot load a polyfill).

A partial solution I made to use promises can be read below.

Promises are the best approach for these chained events

index.html

JavaScript

index.js

JavaScript

If you were to paste these two into codepen.io or a similar site you will see that we iteratively step through each message.

The alternative to fix your setTimeout would to nest the setTimeout calls.

Alternative for browser compatibility

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement