2017-09-06 183 views
0

好的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分鐘後的頁面上時,彈出窗口才會觸發。我不想那樣。我想在特定分鐘顯示彈出窗口,給出參考時鐘。

回答

0

你需要找到multiples X

要做到這一點,你可以用modulo operation,所以:

if(minutes % X === 0) { 
    show_popup(); 
} 

模運算將返回之間的休息師b,如果那就是0,那意味着bmult a iple

例如,如果你想每3分鐘顯示:

1 % 3 = 1 
2 % 3 = 2 
3 % 3 = 0 //show 
4 % 3 = 1 
5 % 3 = 2 
6 % 3 = 0 //show 

等等......

+0

不客氣,很高興提供幫助。 –

0

兩種方式,只需運行代碼才能看到效果(在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)