问题描述
如何检查 if 条件5秒钟?这个 if 条件应该为5秒才能执行其代码。
How to check an if condition for 5 seconds? This if condition should be true for 5 seconds to execute its code.
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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Test SMS Triggers</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
推荐答案
您可以使用来处理给定元素的更改。
You can use MutationObservers to handle changes of a given element.
更新:看到您之前的问题,我改变了答案,因为我认为我误判了您想要做的事情。它现在执行以下操作:
Update: Seeing your previous question, I changed my answer, as I think I misjudged what you wanted to do. It now does the following:
- 等待元素的
innerText
从'0'
到'1'
如果它保持'1'
持续5秒,触发回调
- wait for an element's
innerText
to transition from'0'
to'1'
and if it stays'1'
for 5 seconds, trigger the callback
// 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)));
<h2>Test SMS Triggers</h2>
<p id="demo1">0</p>
<p id="demo2">0</p>
<p id="demo3">0</p>
请注意,根据节点的更改方式,您可能需要摆弄配置。以上我用过:
Note that, depending on how the node is changed, you might need to fiddle with the MutationObserverInit configuration. Above I used:
{ childList: true, characterData: true, subtree: true }
您需要。如果你需要支持旧版本,那么可能还有其他解决方案,但我不敢说出来。 ;)
You'll need at least IE11 for this to work. If you need to support older versions, then there might be other solutions, though I dare not utter them. ;)
为了显示使用更好的工具可以做到这么简单,这里有一个版本:
For the sake of showing how simple this could be done with better tools, here's a rxjs version:
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());
})
;
<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>
这篇关于如何在Javascript中检查条件是否为5秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!