简体   繁体   中英

Run code only during specified period of time

The idea behind these code is to make a watchman that will look for the following two scenarious:

  1. If the the colorChanged was manually enabled before the schedule should began and the time of schedule is over turn off the colorChange.

  2. Turn on the colorChange when the time of schedule is ready.

I did made the code to check for states and change classes, but can't figure out how to make timing function, can you please suggest what can be done in order to achieve that?

 $('.auto-control').click(function(){ $(this).toggleClass('auto-enabled'); $('.target').toggleClass('colorChanged'); }); $('.manual-control').click(function(){ $(this).toggleClass('manual-enabled'); $('.target').toggleClass('colorChanged'); console.log(1) }); setInterval(function() { // 24h format // Scenario 1, currentTime isn't within the schedule and the filter should be turned Off // var currentTime = 14; // Scenario 2, currentTime is within the schedule and the filter should be turned On var currentTime = 16 var startTime = 14; var endTime = 4; // Scenario 1. colorChanged is On if ($('.target').hasClass('colorChanged')) { // Control enabled = True if ($('.auto-control').hasClass('auto-enabled')) { // Current Time is not within the Schedule if (!startTime <= currentTime || !currentTime < endTime) { console.log('time to turn off') $('.target').toggleClass('colorChanged'); $('.manual-control').removeClass('manual-enabled'); } } // Scenario 2. colorChanged is Off } else { // Control enabled = True if ($('.auto-control').hasClass('auto-enabled')) { // Current time is within the Schedule if (startTime <= currentTime || currentTime < endTime) { console.log('time to turn on') $('.target').toggleClass('colorChanged'); } } } }, 1000) 
 .target { width: 50px; height: 50px; background-color: red; } .colorChanged { background-color: green; } button { color: red; } .auto-enabled { color: green; } .manual-enabled { color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class='target'>&nbsp</div> <button class='auto-control'>Auto-control</button> <button class='manual-control'>Manual-control</button> 

I think your main issue is using the ! In front of startTime and currentTime. It will convert them to a Boolean ( true or false) and not work with the times at all.
You should negate the check like so:

if (!(startTime <= currentTime || currentTime < endTime)) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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