我有一个测试代码来检查动态id值以触发sms功能。如果任何id的最后一个值为0且当前值为1,则它将触发sms函数。但是我想在这段代码中添加一个逻辑,如果最后一个值是0,当前值是1,持续5秒,那么只有这个sms函数才会触发。 以下是代码
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) {
console.log('Precheck condition for : ' + elementID + ':' + smstext + '!!!');
setTimeout(function() {
console.log("Rechecking same condition after 5 seconds");
if (previous == 0 && current == 1) {
console.log('Sending SMS for : ' + elementID + ':' + smstext + '!!!');
}
}, 5000);
}
//check conditions again after 5 seconds.
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);
}, 10000);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test SMS</title>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h2>Test SMS Triggers</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script src="index.js"></script>
</body>
</html>
请帮忙。谢谢!
答案 0 :(得分:0)
可以使用javascript setTimeInterval(expression,interval)
函数完成。
将间隔设为5秒.5秒后调用函数来检查值。如果值仍为1,则发送短信更新。