首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Javascript [Chrome扩展]开发中使用setInterval

如何在Javascript [Chrome扩展]开发中使用setInterval
EN

Stack Overflow用户
提问于 2021-09-11 20:14:10
回答 1查看 44关注 0票数 0

我正在学习如何制作chrome扩展,我正在做的项目是一个新标签中的“时钟”。

问题:我可以检索当前时间,但不能每秒刷新页面。我该如何解决这个问题呢?

main.js

代码语言:javascript
复制
setInterval(function () {
  var d = new Date();

  const h = d.getHours();
  const m = d.getMinutes();
  const s = d.getSeconds();

  // Current Time w/ format
  const cFormat = h + ":" + m;

  const cTime = document.getElementById("cTime");
  cTime.textContent = cFormat;
}, 1000);

manifest.json

代码语言:javascript
复制
{
    "manifest_version": 3,
    "name": "ClockTab",
    "description": "Clock.",
    "version": "1.0.0",
    "persistent": true,
    "icons": {"128": "icon_128.png"},
    "host_permissions": ["<all_urls>","activeTab","tabs"],
    "action" : {
        "default_popup": "popup.html",
        "default_icon": "icon_128.png"
    },
    "chrome_url_overrides" : {
        "newtab": "index.html"
    },
    "background": {
        "service_worker": "main.js",
    },
    "content_scripts": [{
        "css": ["style.css","popup.css"],
        "js": ["jquery.min.js", "main.js", "popup.js","dateTime.js"],
        "all_frames": true,
        "matches": ["http://*/*"]
    }]
}

index.html

代码语言:javascript
复制
<div id="cTime"></div>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-11 20:59:49

我选择了setTimeout,允许时钟每秒刷新一次,只有在页面加载之后才会发生。

main.js

代码语言:javascript
复制
function start() {

  // Clock
  function getTime() {
    var d = new Date();

    const h = d.getHours();
    const m = d.getMinutes();
    const s = d.getSeconds();

    // Current Time w/ format
    const cFormat = h + ":" + m;

    const cTime = document.getElementById("cTime");
    cTime.textContent = cFormat;

    setTimeout(function () {
      getTime();
    }, 1000);
  }

  getTime();
}

window.addEventListener("load", start);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69146408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档