微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

        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')}`;
                }});

}

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

解决方法

JavaScript 倒数计时器

代码中的错误:一个 int eventId 值是通过 PubNub 发布的。这不是预期的设计。其原因在使用 setInterval 函数返回间隔计时器的 eventId 后进行了解释。

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

JavaScript Countdown Timer

推荐方法:

(()=>{
'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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。