如何在Javascript中检查条件是否为5秒

时间:2018-04-27 07:37:42

标签: javascript

如何检查 if 条件5秒钟?这个 if 条件应该为5秒才能执行其代码。

WEB_APP

编辑:

function checkcodition() {
  var a,b;
  if (a == 0 && b == 1) // <--this condition should be true for 5 seconds ??
  {
    console.log(" This line should display after 5 seconds");
  }
}
function valupdate() {
  $('p').each(function(index, element) {
    var number = Math.round(Math.random());
    $(element).text(number);
  });
}
valupdate();

// cache DOM elements for quick reference
var demo1 = $('#demo1');
var demo2 = $('#demo2');
var demo3 = $('#demo3');

// store their current values in object
// this is how we will reference their previous values
var stored_values = {
  demo1: demo1.text(),
  demo2: demo2.text(),
  demo3: demo3.text()
};

// loop through all elements
// get their current value from .text()
// get their PREVIOUS value from the object we made above
// compare values with our custom compare function (define below)
// finally, save the current value in our object
function checkValues(item, msg) {
  var element_id = item.attr('id');
  var currentValue = item.text();
  var previousValue = stored_values[element_id];
  compareValues(currentValue, previousValue, element_id, msg);
  stored_values[element_id] = currentValue;
}

// compare values passed in, and determine what to do
function compareValues(current, previous, elementID, smstext) {
  if (previous == 0 && current == 1) //check conditions for 5 seconds to execute below code.
  {
    console.log('Sending SMS for : ' + elementID + ':' + smstext + '!!!');
  }
  else {
    return; // do nothing
  }
}

var msg1 = "Message1";
var msg2 = "Message2";
var msg3 = "Message3";

setInterval(function() {
  valupdate();
}, 1000);

setInterval(function() {
  checkValues(demo1, msg1);
  //checkValues(demo2,msg2);
  //checkValues(demo3,msg3);
}, 5000);

2 个答案:

答案 0 :(得分:1)

您可以使用MutationObservers来处理给定元素的更改。

更新:看到您之前的问题,我改变了答案,因为我认为我错误地判断了您想要做什么。它现在执行以下操作:

  • 等待某个元素的innerText'0'转换为'1',如果它保持'1' 5秒,则触发回调

&#13;
&#13;
// randomly change values
(function valUpdate() {
  Array.from(document.querySelectorAll('p')).forEach((el) => {
    el.innerText = Math.round(Math.random());
  });

  setTimeout(valUpdate, 1000);
})();


// helpers

const onMutation = (target, cb, config = {childList: true, characterData: true, subtree: true}) => {
  const observer = new MutationObserver((mutations) => {
    cb(target, observer.disconnect.bind(observer), mutations);
  });

  observer.observe(target, config);
};

const onChange = (selector) => (target, cb) => {
  let prev = selector(target);

  onMutation(target, (_, disconnect) => {
    const current = selector(target);

    if (prev !== current) {
      cb(prev, current, target, disconnect);
    }

    prev = current;
  });
};

const ifStatic = (decider) => (time, cb) => {
  let to;

  return (...args) => {
    if (decider(...args)) {
      to = setTimeout(cb, time, ...args);
    } else {
      clearTimeout(to);
    }
  };
};

// setup

const onInnerTextChange = onChange((el) => el.innerText);
const ifValidFor = ifStatic((prev, current) => prev === '0' && current === '1');
const sendSms = (message, stop = false) => (prev, current, el, done) => {
  console.log('Sending SMS for:', el.id, 'Message', message);
  stop && done();
};

onInnerTextChange(document.querySelector('#demo1'), ifValidFor(5000, sendSms('Message 1')));
onInnerTextChange(document.querySelector('#demo2'), ifValidFor(5000, sendSms('Message 2', true)));
onInnerTextChange(document.querySelector('#demo3'), ifValidFor(5000, sendSms('Message 3', true)));
&#13;
<h2>Test SMS Triggers</h2>
<p id="demo1">0</p>
<p id="demo2">0</p>
<p id="demo3">0</p>
&#13;
&#13;
&#13;

请注意,根据节点的更改方式,您可能需要摆弄MutationObserverInit配置。以上我用过:

{ childList: true, characterData: true, subtree: true }

您需要at least IE11 for this to work。如果你需要支持旧版本,那么可能还有其他解决方案,但我不敢说出来。 ;)


为了说明使用更好的工具可以做到多么简单,这里有一个rxjs版本:

&#13;
&#13;
const { Observable } = Rx;

const fromMutation = (target, config) => new Observable((observer) => {
  const mutationObserver = new MutationObserver((mutations) => {
    observer.next(mutations);
  });

  mutationObserver.observe(target, config);

  return () => {
    mutationObserver.disconnect();
  };
});

const sendSmsAfter = (delay) => (el) => fromMutation(el, {characterData: true, childList: true, subtree: true})
  .map(() => el.innerText)
  .startWith(el.innerText)
  .distinctUntilChanged()
  .pairwise()
  .switchMap(([prev, current]) => prev === '0' && current === '1'
    ? Observable.of(el).delay(delay)
    : Observable.empty()
  )
;

const elements = document.querySelectorAll('#demo1, #demo2, #demo3');

Observable
  .from(elements)
  .mergeMap(sendSmsAfter(5000))
  .subscribe((el) => {
    console.log('sms go!', el.id);
  })
;

Observable
  .interval(1000)
  .switchMapTo(elements)
  .subscribe((el) => {
    el.innerText = Math.round(Math.random());
  })
;
&#13;
<script src="https://unpkg.com/@reactivex/rxjs@^5/dist/global/Rx.min.js"></script>

<h2>Test SMS Triggers</h2>
<p id="demo1">0</p>
<p id="demo2">0</p>
<p id="demo3">0</p>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

您应该使用浏览器API setTimeout功能。

此示例仅在五秒后检查条件,而不是在五秒间隔期间检查。如果要确保在整个时间间隔内条件保持为真,则应该实现一些onValueChange()类型事件。

function checkCodition() {
    let a, b;
    setTimeout(() => {
        if (a === 0 && b === 1) {
            console.log(" This line shoud display after 5 seconds");
        }
    }, 5000);
}

其他信息:

你应该使用tripple等号===,使用let而不是varcamelCase lowercase为函数名称。