写一个js倒计时2分钟
时间: 2024-05-16 12:12:08 浏览: 14
Sure, here's some code for a 2-minute JavaScript timer:
```
// Set the date and time 2 minutes from now
var countDownDate = new Date().getTime() + (2 * 60 * 1000);
// Update the count down every second
var x = setInterval(function() {
// Get the current time
var now = new Date().getTime();
// Calculate the distance between now and the count down date
var distance = countDownDate - now;
// Calculate minutes and seconds
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result
console.log(minutes + "m " + seconds + "s ");
// If the count down is finished, clear the interval
if (distance < 0) {
clearInterval(x);
console.log("Time is up!");
}
}, 1000);
```
This code creates a new date object with the current time plus 2 minutes. It then uses setInterval to update the timer every second. The current time is compared to the count down time to calculate the remaining minutes and seconds, which are then displayed in the console. When the count down is finished, the interval is cleared and "Time is up!" is displayed in the console.
相关推荐
![html](https://img-home.csdnimg.cn/images/20210720083451.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)