[英]Prevent setTimeout function from running when page on load in javascript
我的 postgres 数据库中有一个学生表(学生),如下所示:
ID | 名 | 姓 | 时间提醒 |
---|---|---|---|
1 | pers1 | pers1_name | 2022-07-30 21:30 |
2 | pers2 | pers2_name | 2022-07-30 20:38 |
我正在研究 laravel 并使用我的 controller 来填充 html 下表是我的 ZFC35FDC7830D5FC69D2E362
<table class="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>
这里的问题是,当加载页面或刷新页面时,脚本会自动触发,那么如何防止呢? 请有任何建议。
修改您的脚本并检查您的日期差异是否为负:
<script>
function test() {
alert('its time');
}
const alertAfter = new Date('{{ $student->time_remind}}') - new Date();
if (alertAfter > 0) {
setTimeout(test, alertAfter)
}
</script>
根据@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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.