简体   繁体   English

我可以在一个总是每秒运行的计时器内每 20 秒调用一次动作吗

[英]Can i call a action in every 20 second inside a timer which is always running in every second

I need to print a console in every 20 second(technically i will call a action in reactjs) inside a interval which is running in every second.我需要在每秒运行的间隔内每 20 秒打印一次控制台(从技术上讲,我将在 reactjs 中调用一个动作)。 this is a dummy code not functioning properly.这是一个无法正常运行的虚拟代码。

var intervalDuration = 200;
    var hitOnEvery = 20;
    setInterval(() => {
         interValDuration -= 1;
          if (interValDuration >= 0) {
            setTimeout(()=>{
                console.log(interValDuration , 'Hit on every' + hitOnEvery + 'second')
            },hitOnEvery);
          } 
       console.log('This will print every '+intervalDuration +'count in a place')
    }, 1000);

can someone correct and help me.有人可以纠正并帮助我。

You can do it like this:你可以这样做:

 var interValDuration = 200; var hitOnEvery = 20; setInterval(() => { interValDuration -= 1; if (interValDuration % hitOnEvery == 0) { console.log(interValDuration, 'Hit on every' + hitOnEvery + 'second') } console.log('This will print every '+interValDuration +'count in a place') }, 1000);

Basically check if interValDuration divided by hitOnEvery has 0 leftover after division, meaning every 20sec perform action基本上检查interValDuration除以hitOnEvery后是否有0剩余,这意味着每20秒执行一次动作

Here is the closure function, for the generic usage这是闭包 function,用于通用用法

 const timer = (() => { let timer; let seconds = 1; return (func, hitAtTime) => { let stopTimer = () => { console.log(timer); window.clearInterval(timer); }; const startTimer = () => { timer = window.setInterval(() => { console.log("i run every second"); seconds++; if (seconds % hitAtTime === 0) { func(); } }, 1000); }; return { stopTimer: stopTimer, startTimer: startTimer, }; }; })(); timer(() => console.log("i run every 10 seconds"), 10).startTimer();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM