[英]Javascript run function one time in another function which sets as interval
嗨,我在我的 js 中使用 selenium chrome 驅動程序。 我每 2 秒檢查一次網站的價值。 這是我的代碼。 值是每 2 秒檢查一次。 它有兩個價值。 喜歡在線或離線。 我想寫入文本文件以更改狀態。 不是每次檢查。 這是我的代碼。 它正在工作,但它每兩秒保存一次文本文件。 我想每兩秒檢查一次,但我想將它保存在僅文本狀態更改中。 請幫幫我。
setInterval(MyControl, 2000);
function MyControl() {
var x = browser.findElements(By.className("textclass")).then(function(divs) {
// console.log("yy:",divs.length);
var d = new Date();
if (divs.length == 1) {
divs.forEach(function(element) {
element.getAttribute("title").then(function(text) {
console.log(text, " Control Time :", d.toLocaleString());
// playSound();
fs.appendFile('mytextfile.txt', text + " Control Time: " + d.toLocaleString() + '\n', function(err) {
// console.log("/////////////////////////////////////");
if (err) throw err;
});
});
});
} else {
console.log("There isnt any info :" + "Control Time :" + d.toLocaleString());
}
});
}
簡單地以當前值是否與先前值不同為條件寫入文件。
setInterval(MyControl, 2000);
let previousText = null;
function MyControl() {
var x = browser.findElements(By.className("textclass")).then(function (divs) {
// console.log("yy:",divs.length);
var d = new Date();
if (divs.length == 1) {
divs.forEach(function (element) {
element.getAttribute("title").then(function (text) {
console.log(text, " Control Time :", d.toLocaleString());
// playSound();
if (text != previousText)
fs.appendFile('mytextfile.txt', text + " Control Time: " + d.toLocaleString() + '\n', function (err) {
// console.log("/////////////////////////////////////");
if (err) throw err;
});
previousText = text;
});
});
} else {
console.log("There isnt any info :" + "Control Time :" + d.toLocaleString());
}
});
}
另請注意,上面以適當的 JS 樣式重寫的代碼更具可讀性:
setInterval(MyControl, 2000);
let previousText = null;
function MyControl() {
browser.findElements(By.className('textclass')).then(divs => {
if (divs.length !== 1)
return;
let date = new Date();
div[0].getAttribute('title').then(text => {
if (text !== previousText)
fs.appendFile('mytextfile.txt', `${text} Control Time: ${date.toLocaleString()}\n`, err => {
if (err) throw err;
});
previousText = text;
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.