[Learning]#28 JS: Timing Events — Part 2

Vida Lin
2 min readOct 18, 2021

--

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

Clap/Share/Follow

If you guys find this article helpful, please kindly do the writer a favor — giving 5 clicks at the GREEN area and 10~50 claps at the bottom of this page.

Most important of all, feel free to comment and share your ideas below to learn together!

--

--

Vida Lin

PM, Relationship, Travel, or anything quirky but interesting.|Subscribe & buy Vida a drink @LikerLand, the bottom of each article. 在文章底下LikerLand訂閱、請Vida喝一杯飲料 ❤