首页 > 解决方案 > 即使浏览器最小化,如何运行我的 JS 脚本?

问题描述

我是JS的新手。我正在编写一个小的 JS/PHP 脚本(wordpress)来每秒增加一个 DB 中的计数器(HTML mp3 播放器的播放时间跟踪)。

主要思想是每次玩家的“当前时间”发生变化时,我都会增加我的数据库计数器。

在我切换到其他浏览器选项卡或计算机上的其他应用程序之前,该代码似乎运行良好。

知道为什么代码仅在我在播放器选项卡上运行时才运行吗?

注意:为了调试,我将所有内容都放入函数 test3() 并在控制台中手动调用它。

谢谢你的帮助

function test3() {

    currentTime = clean(document.getElementsByClassName('hap-media-time-current')[0].innerHTML);
    currentTime = parseInt(currentTime, 10);
    var post_id = "5615";

    $("body").on('DOMSubtreeModified', ".hap-media-time-current", function (event) {
        currentTime = clean(document.getElementsByClassName('hap-media-time-current')[0].innerHTML);
        currentTime = parseInt(currentTime, 10);
        newTime = currentTime;

        if (oldtime == currentTime) {
            //console.log(currentTime);
            //oldtime = currentTime;
        } else {
            if (!isNaN(currentTime)) {
                console.log(currentTime);

                $.ajax({
                    url: postclick.ajax_url,
                    type: 'post',
                    data: {
                        action: 'post_playback_time',
                        post_id: post_id
                    },
                    success: function (response) {
                        //
                    }
                });
                oldtime = currentTime;
            }
        }
    });
}

即使浏览器在后台,我也希望增加

标签: jquery

解决方案


您必须在 setTimeout 中插入函数,而不是在事件中:

setTimeout(function(){
     test3();
}, 100);

在此示例中,我每 100 毫秒调用一次 setTimeout,但您可以根据需要进行调整。


推荐阅读