如何在 pubnub 发布和订阅方法中显示实时时钟

How to show real timer clock in pubnub publish and subscribe method

        let timer =0;
    function showTime() {
        var d = new Date();
        document.getElementById("demo").innerHTML = d.toLocaleTimeString();
    }
    function letsGo(duration) {
        const pubnub = new PubNub({
            publishKey: 'pub-c-1bda0482-9e4d-4ae7-b95d-232b2d452050',
            subscribeKey: 'sub-c-e515c58a-69e0-11eb-b914-eedc703588a5',
            uuid: "myUniqueUUID"
        });
        var timer = duration;
            function  publishSampleMessage(){
                    var publishPayload ={
                        channel : "game-time",
                        message: {
                            data:setInterval(function () {
                            var  minutes, seconds;
                            if(timer>0)
                            {
                            minutes = parseInt(timer / 60, 10);
                            seconds = parseInt(timer % 60, 10);
                            minutes = minutes < 10 ? "0" + minutes : minutes;
                            seconds = seconds < 10 ? "0" + seconds : seconds;
                            //console.log(minutes+":"+seconds);
                            document.getElementById("demo").innerHTML = minutes + "m " + seconds + "s ";
                            timer--;                     
                            if (timer==0) {
                            
                                document.getElementById("demo").innerHTML ="Game is Over";
                                document.getElementById("game").innerHTML ="";                          
                            }
                            //timesender(timer);
                        }
                       
                    }, 1000),
                        mytime: --timer
                    }
                }
                pubnub.publish(publishPayload, function(status, response) {
                console.info("status publish function "+status);
                console.info("response publish function "+ response.timetoken);
                console.info(publishPayload);
                })
            }
            pubnub.addListener({
                status: function(statusEvent) {
                    if (statusEvent.category === "PNConnectedCategory") {
                        publishSampleMessage();
                    }
                },
                message: function(msg) {
                    console.log("sanu ki "+msg.message.data);
                   if(msg.message.mytime>0) {
                       console.log("tanu ki " + msg.message.mytime);
                       msg.message.mytime--;
                   }
                },
                presence: function(presenceEvent) {
                    // This is where you handle presence. Not important for now :)
                    console.log("presence "+presenceEvent.action);
                }
            })
            console.log("Subscribing...");
    
        pubnub.subscribe({
            channels: ['game-time'],
            withPresence: true
        });
        
    }
     function timesender(time){
                        console.log("time is this : "+time);
                    }

我正在尝试通过 javascript 在 PubNub 中发布一个实时倒数计时器,但是每当我发布一条消息时,它看起来就像一个固定数字,比如 6,它永远不会像一个倒计时时钟,但在控制台日志它看起来像一个倒计时时钟。请建议我如何以管理员身份发布倒计时时钟,以便其他用户收听。基本想法是我在 PHP 和 JS 中创建了一个管理门户,我在其中启动了一个倒数计时器,Unity 手机游戏用户将收听该计时器

Stephen 帮助后更新的代码:

     function letsGo(duration) {
            const channel = 'game-time';
            const pubnub = new PubNub({ publishKey : 'pub-c-1bda0482-9e4d-4ae7-b95d-232b2d452050', subscribeKey : 'sub-c-e515c58a-69e0-11eb-b914-eedc703588a5' });
            let countdown = 65; // seconds
            const countdownId = setInterval( countdownUpdate, 1000 );
            function countdownUpdate() {
                pubnub.publish({
                    channel : channel,
                    message : { 'countdown' : --countdown },
                });
                if (countdown <= 0) clearInterval(countdownId);
            }

        console.log("Subscribing...");

// Public user receiving updates on the countdown
            pubnub.subscribe({
                channels: [channel]
            });

            pubnub.addListener({ message: event => {
                    const timeLeft = event.message.countdown;
                    console.log("time left "+timeLeft)
                    const minutes = Math.floor(timeLeft / 60) + '';
                    const seconds = Math.floor(timeLeft % 60) + '';
                    let dd = `${minutes.padStart(2,'0')}:${seconds.padStart(2,'0')}`;
                    document.querySelector('#demo').innerHTML =
                        `${minutes.padStart(2,'0')}:${seconds.padStart(2,'0')}`;
                }});

}

我现在遇到了一个小问题。基本上我在点击按钮上创建了一个 letsGo 函数,所以每当我在另一个浏览器中打开一个计时器页面时,我都会得到两个时钟,一个是前一个浏览器的延续,但另一个是从头开始的

JavaScript倒数计时器

The bug in the code: an int eventId value is published via PubNub. This isn't the intended design. The reason for this is explained following usage of setInterval function returning the eventId for the interval timer.

let eventId = setInterval(...) returns 一个引用浏览器事件循环堆栈上的 setInterval eventId 的整数。这个想法是您可以使用 eventId 稍后通过 clearInterval(eventId).

停止间隔

推荐方法:

(()=>{
'use strict';

const channel = 'game-time';
const pubnub = new PubNub({ publishKey : 'demo', subscribeKey : 'demo' });
let countdown = 65; // seconds
const countdownId = setInterval( countdownUpdate, 1000 );

// Secure Server --> this should be running on your node.js server.
function countdownUpdate() {
    pubnub.publish({
        channel : channel,
        message : { 'countdown' : --countdown },
    });
    if (countdown <= 0) clearInterval(countdownId);
}

// Public user receiving updates on the countdown
pubnub.subscribe({
    channels: [channel]
});

pubnub.addListener({ message: event => {
    const timeLeft = event.message.countdown;
    const minutes = Math.floor(timeLeft / 60) + '';
    const seconds = Math.floor(timeLeft % 60) + '';
    document.querySelector('#timer').innerHTML =
        `${minutes.padStart(2,'0')}:${seconds.padStart(2,'0')}`;
}});

})();
#timer {
    font-size: 60px;
}
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.29.11.min.js"></script>
<div id="timer">00:00</div>