• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

关于JavaScript/TypeScript中的setTimeout和setInterval

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

ypescript是强类型语言,定义setInterval()必须定义其返回值,但是你无论用百度或者谷歌搜中文也好英文也罢,都告诉你setInterval()的返回值类型是number,

如果你将setInterval()定义成number型,会告诉你不能将类型“Timeout”分配给类型“number”,但是如果定义成所谓的“Timeout”型,也就是“NodeJS.Timeout”型初期化又成了问题

那么要这么定义:

public timer: NodeJS.Timer | null = null;

但是不能完全照搬因为这么定义的话

clearInterval(timer)时参数类型会出问题,所以要将参数强制转换成number型

也就是clearInterval(Number(timer))。

例:

数组只要含有 curTimes字段就创建一个定时器,多个定时器同时倒计时,若该时间大于当前时间则清楚该定时器

  this.list.map((itemSec, indexSec) => {
            let _this = this;
            if (itemSec.curTimes) {
              itemSec.timer = setInterval(() => {
                var my_time: any = new Date(Number(itemSec.curTimes)).getTime();
                var my_time2: any = new Date().getTime();
                var mss: any = Number(itemSec.curTimes) - Number(my_time2);
                if (Number(my_time) - Number(my_time2) <= 0) {
                  itemSec.timer && clearInterval(itemSec.timer);
                  itemSec.currentHours = 0;
                  itemSec.currentSecond = 0;
                  itemSec.currentMinutes = 0;
                  return;
                }
                var hours: any = Math.floor(
                  (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
                );
                var minutes: any = Math.floor(
                  (mss % (1000 * 60 * 60)) / (1000 * 60)
                );
                var seconds: any = Math.floor((mss % (1000 * 60)) / 1000);
                if (minutes < 10) {
                  minutes = "0" + minutes;
                }
                if (seconds < 10) {
                  seconds = "0" + Number(seconds);
                } else {
                  seconds = Number(seconds);
                }
                itemSec.currentHours = hours;
                itemSec.currentSecond = seconds;
                itemSec.currentMinutes = minutes;
              
              }, 1000);
            }
          });

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Vue3.x+TypeScript安装初体验发布时间:2022-07-18
下一篇:
typescript(一)发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap