简体   繁体   English

JavaScript时钟:时间间隔冲突

[英]JavaScript clock: time interval conflicts

Hi I'm new to programming and am working on a JavaScript clock. 嗨,我是编程新手,正在使用JavaScript时钟。 I got it to change background color depending on whether it's an even or odd minute, and it changes text color every hour. 我知道它是根据分钟是偶数还是奇数来更改背景颜色,并且每小时都会更改文本颜色。 However, I'm having trouble integrating a third task in: I'm trying to get it to change to a random color every five minutes, thus overriding the even-or-odd statements. 但是,我在集成第三个任务时遇到了麻烦:我试图让它每五分钟更改为随机颜色,从而覆盖偶数或奇数语句。 So minute 1: odd, minute 2: even, 3: odd, 4: even, 5: RANDOM COLOR. 所以分钟1:奇数,分钟2:偶数,3:奇数,4:偶数,5:随机颜色。

Since the function to change the background color every five minutes ( lines 75 to 83 ) is set on an interval, that conflicts with the interval set for getting the date ( line 71 ). 由于每隔五分钟更改背景颜色的功能( 第75至83行 )是按间隔设置的,因此该间隔与为获取日期而设置的间隔( 第71行 )相冲突。

As it stands now, the effects of Tasks 2 and 3 are not visible until Task 1 is commented out. 目前,任务2和3的效果直到任务1被注释掉后才可见。 Is there a way to perhaps combine Task 1 with the if/else statement on lines 11-24, so that all my tasks can run concurrently? 有没有一种方法可以将任务1与第11-24行的if / else语句组合在一起,以便我的所有任务可以同时运行?

Use a single timer function to carry out all events. 使用单个计时器功能执行所有事件。 To get more accurate timing, set your timer to execute once every 100 milliseconds and maintain a counter. 为了获得更准确的计时,请将计时器设置为每100毫秒执行一次并维护一个计数器。 Based on the counter value, you can execute specific tasks at various intervals and also check for overlap of intervals. 根据计数器值,您可以按不同的时间间隔执行特定任务,还可以检查时间间隔是否重叠。 The counter can be reset when it reaches the largest interval you need to track. 当计数器达到您需要跟踪的最大间隔时,可以将其重置。

Here is a sample: 这是一个示例:

var counter = 0;
var oldsec = 0;
setInterval(function(){timerInt()}, 100);

function timerInt(){
    // Read system clock and get seconds
    if (seconds <> oldsec) {
        // Update clock time here and set oldsec=seconds
    }


    // Execute other tasks
    if (counter % 3000 == 0) {  // Executes once every 5 minutes (300*10)

    }
    else if (counter % 1200 == 0) {  // Executes once in 2 minutes (120*10)

    }
    else if (counter % 600 == 0) {  // Executes once a minute (60*10)

    }

    counter += 1;
    if (counter == 3000) counter = 0;
}

You can use if and else to control which tasks to execute. 您可以使用ifelse控制要执行的任务。 Your clock seconds update will also be more accurate and will not "skip" seconds like it would with a 1000 millisecond timer. 您的时钟秒更新也将更加准确,并且不会像使用1000毫秒计时器那样“跳过”秒。

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

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