iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0
Modern Web

Learn & Play JavaScript -- Entry-Level Front-End Web Development系列 第 28

#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

Yes


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


上一篇
#27 JS: Timing Events - Part 1
下一篇
#29 JS: AJAX
系列文
Learn & Play JavaScript -- Entry-Level Front-End Web Development30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言