gpt4 book ai didi

javascript - 需要将参数传递给 setInterval 使用的类方法

转载 作者:行者123 更新时间:2023-11-30 12:13:26 26 4
gpt4 key购买 nike

我在使用 setInterval 方法时遇到了问题,因为我需要将它的第一个参数(设置为间隔的函数)传递给它自己的参数。

我已经包含了我试图实现这一目标的类(class)。

假设该函数本身有效,我从 ajax 得到了响应,但它不知道将它放在哪里。任何人都知道如何实现这一点?

function message_console(log_id, person_2_msg_id) {
this.user_id = log_id;
this.person_messaged_id = person_2_msg_id;
this.input_id = "send_to_" + person_2_msg_id;
this.messages_id = "chat_with_" + person_2_msg_id;

this.get_messages = function get_messages(id) { // remember to add the id as parameter
// to this function that will receive
// this responseText
//ajax here - get messages
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
_(id).innerHTML = x.responseText;
}
}
x.open("POST", "parse/private_msg.php");
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.send("get_messages=true&to=" + person_2_msg_id);
}

setInterval(this.get_messages, 3000); // need to figure out how to pass para here - with
// the function as a variable and in oop - not sure
// how - ask adam asap
setInterval(this.get_messages(parameter), 3000); //this does not work

this.container += '<div class="msg_module">';
this.container += '<div class="message" id="' + this.messages_id + '">' +
this.get_messages(this.messages_id) + '</div>';
this.container += '<input type="text" onkeypress="submit_private_msg(event,\'' +
this.user_id + '\',\'' + this.person_messaged_id + '\',\'' + this.messages_id +
'\',\'' + this.input_id + '\')" class="msg_head" id="' + this.input_id + '" >';
this.container += '</div>';
}

最佳答案

参见 MDN 文档 here , 语法如下:

var intervalID = window.setInterval(func, delay[, param1, param2, ...]);

var intervalID = window.setInterval(code, delay);

选项 1:

setInterval( this.get_messages,3000, parameter);

选项2:

setInterval( function(){ this.get_messages.call(this, parameter) } ,3000 );

函数调用方法见here

关于javascript - 需要将参数传递给 setInterval 使用的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33115834/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com