#28 JS: Timing Events - Part 2

After introducing about the 2 methods for timing events in the last article, let's practice by examples:

Example 1. setTimeout

Usage Scenario: transfer the web page from price comparison to Ads or an e-commerce company's page.

Count down from 3 seconds:
图片

<body onload="init();">
    <span id="timer">3</span> 
 
<script type="text/javascript">
let timer;
function init(){ 
    timer=document.getElementById("timer");
    window.setTimeout(countdown, 1000);
}
 
function countdown (){
    timer.innerHTML=timer.innerHTML-1;
    if(timer.innerHTML>0){ //It will continue counting down until meeting 0.
        window.setTimeout(countdown, 1000);  
    }else{
        document.location="https://vidalin-777.medium.com/";
    }
}
    
</script>
</body>

Example 2. setInterval

Usage Scenario: same as example 1.

Count down from 3 second, same as example 1, but setInterval will continue repeating the function. And we can skip window.setTimeout(countdown, 1000); to simplify the function.

<script type="text/javascript">
let timer;
function init(){ 
    timer=document.getElementById("timer");
    window.setInterval(countdown, 1000); 
}
function countdown (){
    timer.innerHTML=timer.innerHTML-1;
    if(timer.innerHTML>0){
    }else{
        document.location="https://vidalin-777.medium.com/";
    }
}
</script>

Music of Today: Run by Phum Viphurit


Like/Share/Follow

Feel free to comment and share your ideas below to learn together!
If you guys find this article helpful, please kindly do the writer a favor — LIKE this article./images/emoticon/emoticon12.gif


<<:  [Day 17] 第一主餐 pt.9-战前准备

>>:  Day13 Function Component的生命周期 - UseEffect

Day10 Lab说明

接下来就进到Lab环节了,不过第一个会比较简单,有点像是热热身,熟悉一下python和前後端程序 首...

Day13 - this&Object Prototypes Ch3 Objects - Contents - Existence - Enumeration 作者建议

使用 in 搭配 for 时, array 内所有 enumerable 为 true 的 prop...

【在厨房想30天的演算法】Day 15 演算法 : 排序 sort II 堆积、合并、快速

Aloha!又是我少女人妻终於来到第 15 天了~不知不觉就过了一半了,大家有听过跑者愉悦理论吗,就...

Day26 NodeJS中的前端框架 II

今天的内容一样以React为主,建立完前端应用程序之後,接着就是将前後端的应用程序连接。 首先在Re...

DAY30 - 写在30天之後:成为前端工程师一年後的心路历程

终於到最後一天了~~ 刚好从去年铁人赛到今年是我从切版转职走到"更完整的前端工程师&quo...