在从 getJSON 调用返回的数据发生更改时触发事件

Trigger event on change in returned data from getJSON call

本文关键字:事件 在从 调用 返回 数据 getJSON      更新时间:2023-09-26

我有一个getJSON函数,我目前正在调用一次,然后使用setInterval((函数来监听可以随时更改值的 thingspeak.com 频道馈送。

我想在我的 jQuery 代码中触发一个事件,在 getJSON 函数之外,当返回的数据字段 1 的值为"1"时。如果值为"0",则应关闭事件。目前为止,一切都好。但是由于getJSON正在侦听通道源,间隔几秒钟,它将一遍又一遍地触发事件(timer((函数(。

如何让 getJSON 事件"在后台运行",并且仅在通道源返回的数据实际更改时才触发?返回的数据还有一个字段,其中包含数据输入 (entry_id( 的唯一 ID,因此可以侦听此值的更改。

当前正在运行此代码:

$(document).ready(function() {
    getUpdates();
    setInterval('getUpdates()',400);
});
function getUpdates() {
    $.getJSON('http://api.thingspeak.com/channels/xxx/feed/last.json?callback=?', {key: "xxx"}, function(data) {
    if(data.field1 == '1') {
        // trigger timer function on
    } else if(data.field1 == '0') {
        // trigger timer function off
    }
});
function timer() {
    // Starts a timer countdown in a div
}            

这是代码的第二个版本,可能提供更多信息:

$(document).ready(function() {
    getUpdates();
    setInterval('getUpdates()',400);    
});
function getUpdates() {
    var entries = new Array();
    $.getJSON('http://api.thingspeak.com/channels/xxx/feed/last.json?callback=?', {key: "xxx"}, function(data) {
        if ($.inArray(data.entry_id,entries) === -1) {
            //New entry, add the ID to the entries array
            entries.push(data.entry_id);
            //Check if the div should be visible or not
            if(data.field1 == '1') {
                $(".desc").show();
            } else if(data.field1 == '0') {
                $(".desc").hide();
            } 
        } else if ($.inArray(data.entry_id,entries) > -1) {
            // Same entry as previous call, do nothing.
        } 
    });
}
<div class="desc"></div>

这仍然不起作用,因为它似乎不会更新条目数组。

这是一个近似的、未经测试的逻辑(毕竟我无法访问具有正确数据的提要(。让我知道它是否能引导你朝着正确的方向前进。

var timerSet = 0;
function startTimer(){
    timerSet = 1;
    // start the 1-minute timer and show feedback to user
}
function stopTimer(){
    timerSet = 0;
    // stop the 1-minute timer and show feedback to user
}
function getUpdates() {
    var entries = new Array();
    $.getJSON('http://api.thingspeak.com/channels/xxx/feed/last.json?callback=?', {key: "xxx"}, function(data) {
        if ($.inArray(data.entry_id,entries) === -1) {
            //New entry, add the ID to the entries array
            entries.push(data.entry_id);
            // check which state the system is in and manage the 1-minute timer
            if(data.field1 == '1' && timerSet === 0) { // if 1-minute timer not running already - start it
                startTimer();
            } else if(data.field1 == '0' && timerSet === 1) { // if 1-minute timer running already - stop it
                stopTimer();
            } 
        }
    });
}
$(document).ready(function() {
    // getUpdates(); don't need this: function will be called in 400ms anyway
    setInterval('getUpdates()',400);    
});