在由时钟每“X”分钟
问题描述:
好的JavaScript调用功能,所以我有:在由时钟每“X”分钟
function show_popup() {
alert('Ha');
}
现在,我要的是叫每个X分钟此功能,但给作为参考时钟(实时)。
如果X是5,那么下一个功能的正常使用:
setInterval(function(){
var date = new Date();
var minutes = date.getMinutes().toString();
var minutes = minutes.slice(-1); // Get last number
if(minutes == 0 || minutes == 5)
{
show_popup(); // This will show the popup at 00:00, 00:05, 00:10 and so on
}
}, 1000);
我怎样才能让这个功能,如果我改变5分钟到4工作,或3,或20?
我必须指出,我不能从setinterval更改计时器,因为这将意味着只有当您在传递X分钟后的页面上时,弹出窗口才会触发。我不想那样。我想在特定分钟显示弹出窗口,给出参考时钟。
答
你需要找到的multiples X
要做到这一点,你可以用modulo operation,所以:
if(minutes % X === 0) {
show_popup();
}
模运算将返回之间的休息师的和b,如果那就是0,那意味着b是mult a iple。
例如,如果你想每3分钟显示:
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0 //show
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0 //show
等等......
答
两种方式,只需运行代码才能看到效果(在Chrome浏览器)
1.使用计时器,当一个信用降临时,你可以改变周期,定时不是精确
class MyInterval {
constructor(defaultInterval, callback) {
this.interval = defaultInterval
this.callback = callback
this._timeout = null
this.tick()
}
tick() {
const {
interval,
callback
} = this
this._timeout = setTimeout(() => {
callback()
this.tick()
}, interval)
}
stop() {
clearTimeout(this._timeout)
}
changeInterval(interval) {
this.interval = interval
}
}
const myInterval = new MyInterval(1000,() => console.log(new Date()))
setTimeout(() => {
myInterval.changeInterval(2000)
}, 3500)
setTimeout(() => {
myInterval.stop(2000)
}, 13500)
2.使用一个最小间隔,更快速的反应,具有最小的限制,可能会花费更多
class MyInterval {
constructor(minimal, defaultInterval, callback) {
this.minimal = minimal
this.interval = defaultInterval
this.callback = callback
this._current = 0
this._timeout = setInterval(() => {
this._current++
if (this._current >= this.interval) {
this._current = 0
callback()
}
}, minimal)
}
stop() {
clearInterval(this._timeout)
}
changeInterval(interval) {
this.interval = interval
}
}
const myInterval = new MyInterval(1000, 1,() => console.log(new Date()))
setTimeout(() => {
myInterval.changeInterval(2)
}, 3500)
setTimeout(() => {
myInterval.stop()
}, 13500)
不客气,很高兴提供帮助。 –