I have a JavaScript class Timer which counts down to a future date. The constructor accepts a CSS selector and the date in question (a string), i.e., new Timer('#timer',toTime)
. When invoked in a <script>
, however, there seems to be a race condition. Consider the PHP snippet:
$toDate = date(DATE_ATOM, mktime(0, 0, 0, 1, 1, 2024)); // Jan 1st, 2024
echo '<script type="text/javascript">', PHP_EOL;
echo " window.t = new Timer('#timer', '$toDate')", PHP_EOL;
echo '</script>', PHP_EOL;
Looking at the window
object in the console gives t: undefined
. That said, if I set in the script window.t = 1234
, such a value is found (t: 1234
).
There seems to be a race condition when using new
within a <script>
. Does anyone know how to fix it?
It is worth noting that the timer shows on the page just fine, but I don’t have a handle on the JavaScript Timer object and I need to execute some other methods, like stopping the countdown.
2
Answers
My mistake! In reality, the Timer class has methods to count up, down, or just be a clock, which I omitted for the sake of brevity. The relevant call is:
window.t = new Timer('#timer', '$toDate').countDown()
Those methods (
countDown
in this case) were not returningthis
and therefore the return wasundefined
.Based on the information provided, it seems like the issue might be related to the timing of your JavaScript code execution. When the
<script>
block is executed, the Timer object might not have been fully initialized, resulting inwindow.t
being undefined.To resolve this race condition, you can try wrapping your JavaScript code in an event listener that waits for the document to finish loading before executing the Timer initialization. Here’s an example:
By using the
DOMContentLoaded
event, you ensure that the Timer object is initialized only after the HTML document has finished loading. This should help prevent the race condition and ensure thatwindow.t
is properly defined.After making this change, you should be able to access
window.t
and execute any other methods or operations on the Timer object as needed.