Home > other >  Prevent setTimeout function from running when page on load in javascript
Prevent setTimeout function from running when page on load in javascript

Time:08-01

I have a table for students (students) in my postgres database like this :

id first_name last_name time_remind
1 pers1 pers1_name 2022-07-30 21:30
2 pers2 pers2_name 2022-07-30 20:38

I'm working on laravel and I use my controller to fill html table below here is my html blade:

<table  id="timeTable">
  <thead>
    <th>first name</th>
    <th>last name</th>
    <th>remind time</th>
  </thead>
  <tbody>
    @foreach ($students as $student)
      <tr>
        <td>{{$student->first_name}}</td>
        <td>{{$student->last_name}}</td>
        <td>{{$student->time_remind}}</td>
        <script>
            function test() {
               alert('its time');
            }
            setTimeout( test, new Date('{{ $student->time_remind}}') - new Date());
        </script>
      </tr>
    @endforeach
  </tbody>
</table>

The problem here is that when loading the page or refreshing the page, the script fires automatically, so how to prevent that? please any suggestions.

CodePudding user response:

Modify your script and check if your date difference is negative:

<script>
    function test() {
        alert('its time');
    }

    const alertAfter = new Date('{{ $student->time_remind}}') - new Date();

    if (alertAfter > 0) {
        setTimeout(test, alertAfter)
    }
</script>

CodePudding user response:

Based on the answer of @PunyFlash :

<script>
   function test() {
       alert('its time');
   }

   if (new Date('{{ $student->time_remind}}') - new Date()> 0) {
       setTimeout(test, new Date('{{ $student->time_remind}}') - new Date())
   }
</script>
  • Related