jquery - 即使浏览器最小化,如何运行我的 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;
}
}
});
}
即使浏览器在后台,我也希望增加
解决方案
您必须在 setTimeout 中插入函数,而不是在事件中:
setTimeout(function(){
test3();
}, 100);
在此示例中,我每 100 毫秒调用一次 setTimeout,但您可以根据需要进行调整。
推荐阅读
- java - 在 MySQL JDBC 中获取 AUTO_INCREMENT *before* 数据库插入
- java - Junit测试调用rest api的方法
- java - 有没有办法一个可完成的功能在执行完成后通知其他未知(谁正在等待其他功能的结果)?
- ios - 斯威夫特:如果我删除了一个值,如果我再次插入它,为什么还要再次删除 Firebase 这个值?
- powerpoint - PowerPoint 中的 Web 插件对话框:居中和插入 Web 浏览器仿真
- python - 附加到对象列表的项目附加到每个对象的列表
- powershell - 'Rename-Item' 使用新名称制作副本
- angularjs - 在Angular JS中获取ng-options的数组索引
- node.js - 如何配置终端以读取 UTF-8 字符?
- javascript - 如何获得所需的输出?2 输入名字和出生日期?