JavaScript Website Launch Countdown in Laravel

JavaScript Website Launch Countdown in Laravel

In this article, I would like to teach you how you can create a website Launch Timer that looks like the one above.

We will achieve this by first setting a date in our code. But since we don’t want our users to know on which date we planned the launch, we will convert it into milliseconds on the server-side beforehand in PHP.

After we saved our time difference in milliseconds on the server-side, we will inject this parameter into our JavaScript setInterval()-function. This script will then count down the millisecond in our target-div container. In this example, the target div-container has the id #timer.

  1. First we need to find the main view file usually called /resources/views/welcome.blade.php
  2. Next, we find the content-div container with the name <div class="content"> and insert the following code:

<div class="title m-b-md">
    Launch in:
    <div id="timer" style="font-family: monospace;"></div>

        var millis = <?php
        $timestamp = strtotime('2022-01-01');// your launch date
        $difference = $timestamp - time();// difference in seconds
        echo ($difference * 1000); ?>;
        function displaytimer(){
        setInterval(function(){ // counts every millisecond down and updates
            millis -= 1;
        }, 1);

That’s pretty much all we need. For those interested, I’m going to explain the lines further.

The first important line is line 3 which creates a new empty div-cell with font-family: monospace;. We use monospace because otherwise, the display would flicker as the numbers are continuously changing.

After that, the script starts. The first JavaScript variable is the variable millis. Instead of defining it directly, we calculate it on the server backend in PHP from lines 6 to 9.

In the PHP script, we first calculate our target date to a PHP time value. We then calculate the difference between then and now, so that we know how much time is left over. And last, we convert the seconds into milliseconds.

The code continues in JavaScript. In the function displaytimer(), we just update our HTML-div cell.
The only thing we still need is our dynamic countdown. For this purpose, we call the function setInterval(…). The second argument defines, how often the first argument gets executed, in our case every millisecond. And the first argument counts millis down by one and updates the view.

That’s it.

Kommentar verfassen