关于JavaScript/TypeScript中的setTimeout和setInterval
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); } });