javascript setInterval 不是每 30 秒调用一次

javascript setInterval doesn't call every 30 seconds

我有两个函数,我需要它每 30 秒调用一个函数。但是当使用 setInterval 时,它每秒调用一次。我该如何解决这个问题?

this.seconds = 30; // part of a class called "player" it holds a value in seconds
var _seconds = this.seconds * 1000; // converts seconds to miliseconds

this.init = function() {
    ws.send('init'); // sends "init" to the server
}

ws.onopen = function() { // ws is a local variable that holds the connection.
//ws.onopen is a method of ws it is called once per page load,
//and only if the client connects successfully to the server 
    var call = this.init;
    setInterval(call, _seconds);
}

试试这个,改用你的函数名 call_function

setInterval(function(){
  call_function();
}, 30000);

查看您的代码,您是如何调用 ws.onopen 的?目前,当您调用该函数时,我相信 this 上下文绑定到 ws。但是,您的 ws 对象没有与之关联的 init 方法。

你必须小心 JavaScript 中的 setTimeout 和 setInterval 函数。例如,setInterval 函数不会每 X 秒调用一次您的函数。它所做的是每隔 X 秒,它会将您的函数放入事件队列中。只有当特定函数轮到队列中时,它才会被执行。我知道这不一定是您问题的答案,但我相信您的问题存在轻微缺陷,因为您无法从本质上保证使用 setInterval 每 30 秒调用一次函数。