简体   繁体   English

如何解决electron的setInterval无效问题?

[英]How to solve the invalid problem of electron's setInterval?

I encountered a difficult problem when trying to write an electron application.我在尝试编写 electron 应用程序时遇到了一个难题。 The following is a detailed description of the problem: I plan to load a clock on the page of the electron rendering process.下面是问题的详细描述:我打算在electron渲染过程的页面加载一个时钟。 Just like our system time, it will refresh every second, 60 seconds is one minute, and so on, but I don't use the system time, I use a current Time API, the json data returned by this API interface is the current time.就像我们的系统时间一样,会每秒刷新一次,60秒就是一分钟,以此类推,但是我没有使用系统时间,我使用的是当前时间API,这个API这个ZDB974238714CA8DE634A7CE1D0接口返回的数据json数据是当前的时间。 I wrote a set of asynchronous execution functions in the main process main.js to get the data passed by this API.我在主进程main.js中写了一组异步执行函数来获取这个API传过来的数据。 The following is the main process main.js Asynchronous get time API code:以下是主流程main.js异步获取时间API代码:

const request = net.request('http://api.k780.com:88/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json')

  request.on('response', (response) => {
    console.log(response.statusCode);
    console.log(response.headers);

    response.on('data', (chunk) => {
      let result = JSON.parse(chunk).result;
      let datetime = result.datetime_1;
      let week = result.week_4;
      console.log(datetime, week)
      mainWindow.webContents.send('datetime', { datetime, week });
    })

    response.on('end', () => {
      console.log('end');

    })

  })
  request.end();

The console information displayed by the main process is as follows:主进程显示的控制台信息如下:

200
{
  server: 'nginx',
  date: 'Thu, 06 May 2021 01:38:00 GMT',
  'content-type': 'application/json; charset=utf-8;',
  'transfer-encoding': 'chunked',
  connection: 'keep-alive',
  'access-control-allow-origin': '*'
}
2021-05-06 09:38:01 Thursday
end

Then after requesting this API, it will respond with a timestamp of the current time.然后在请求这个 API 之后,它会以当前时间的时间戳进行响应。 After the main process obtains this timestamp, it will be sent to my rendering process through webContents.send.主进程获取到这个时间戳后,会通过webContents.send发送给我的渲染进程。 The following is the code sent by the main process to the rendering process:以下是主进程发送给渲染进程的代码:

mainWindow.webContents.send('datetime', { datetime, week });

The rendering process obtains the time data sent by the main process through ipcRenderer.on, and then formats this timestamp and outputs it to my rendering process page.渲染进程通过ipcRenderer.on获取主进程发送的时间数据,然后将这个时间戳格式化输出到我的渲染进程页面。 I wrote this set of code as a function as follows:我把这组代码写成 function 如下:

function getNetTime() {
    //Get the date and time passed by the main process
        ipcRenderer.on('datetime', (event, arg) => {
            let datetime = arg.datetime; //Get date and time
            let week = arg.week; //Get the day of the week
            let year = datetime.substring(0, 4); //Get year
            let month = datetime.substring(5, 7); //Get month
            let day = datetime.substring(8, 10); //Get the day
            let hour = datetime.substring(10, 13); //Get hour
            let min = datetime.substring(14, 16); //Get minutes
            let sec = datetime.substring(17, 19); //Get seconds
            let weekday = ""; //Get Chinese weekday
            const timeText = document.querySelector('#timeText')
            // console.log(datetime);
            // console.log(week);
            // console.log(year,month,day,hour,min);
            switch (week) {
                case'Monday':
                    weekday ='Monday';
                    break;
                case'Tuesday':
                    weekday ='Tuesday';
                    break;
                case'Wednesday':
                    weekday ='Wednesday';
                    break;
                case'Thursday':
                    weekday ='Thursday';
                    break;
                case'Friday':
                    weekday ='Friday';
                    break;
                case'Saturday':
                    weekday ='Saturday';
                    break;
                case'Sunday':
                    weekday ='Sunday';
                    break;
            }
            timeText.innerHTML =`${year}year${month}month${day}day ${weekday}${hour}:${min}:${sec}`;

        });

The problem now encountered is that although the current time can be displayed normally on the page of the rendering process, it cannot be automatically refreshed.现在遇到的问题是当前时间虽然可以在渲染进程的页面上正常显示,但是不能自动刷新。 I want to set it to refresh every 1000 milliseconds through setTimeout or setInterval, which is equivalent to one step in 1 second of the clock.我想通过setTimeout或者setInterval设置它每1000毫秒刷新一次,相当于时钟的1秒走一步。 But it has no effect.但它没有效果。 The current time can only be displayed when the program is reopened, and it cannot be automatically refreshed.当前时间只能在程序重新打开时显示,不能自动刷新。 The following is the code of setInterval:下面是setInterval的代码:

window.onload = () => {
    getNetTime();
    setInterval(getNetTime(),1000)
    
}

The above is the problem I am encountering now.以上就是我现在遇到的问题。 Electron is also just getting in touch. Electron 也刚刚取得联系。 I am searching for a long time on net.我在网上找了很久。 But no use.但是没有用。 Please help or try to give some ideas how to achieve this.请帮助或尝试提供一些想法如何实现这一目标。

The problem you're experiencing has nothing to do with Electron or how you request the data from the API.您遇到的问题与 Electron 或您如何从 API 请求数据无关。 It's about how you set your interval.这是关于你如何设置你的间隔。

The setInterval() function requires a function or a string of code as a parameter. setInterval() function需要一个 function 或一串代码作为参数。 However, you are specifying getNetTime() as the code it should call.但是,您指定getNetTime()作为它应该调用的代码。 This is not a function.这不是 function。 It is a function call and will be evaluated before setInterval() is called.这是一个function 调用,将在调用setInterval()之前进行评估。 This will not do anything because the return type of getNetTime() is undefined .这不会做任何事情,因为getNetTime()的返回类型是undefined

To mitigate this, you can use a function, an arrow function or just leave out the parentheses.为了缓解这种情况,您可以使用 function、箭头 function 或省略括号。 Whatever you choose is up to your liking.无论您选择什么,都取决于您的喜好。

setInterval (getNetTime, 1000);
// or
setInterval (() => getNetTime (), 1000);
// or
setInterval (function () { getNetTime (); }, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM