我试图阻止setInterval函数在用户取消选择他们选择的div但我无法使其工作时运行。有什么想法吗?`
我已经尝试了清除间隔,但这不起作用。我也尝试使用 this 中的cvalue,但它不会在代码中更新。
$(document).on("click",".profTemp", function()
{
var pollUser;
if(!$(this).hasClass('selected'))
{
var selectedUser;
var previous = null;
var current = null;
var assigned = false;
selectedUser = $(this).children('span').text();
selectedUser = selectedUser.trim();
//selectedUser = $(this).children('span').text();
console.log(selectedUser);
$(this).toggleClass('selected');
//selectedUser = selectedUser.trim();
pollUser = setInterval(function()
{
console.log(selectedUser);
$.ajax({
url: '/getJSON',
dataType: 'json',
success: function(response) {
console.log(response + "84897348");
obj = JSON.parse(response);
console.log(selectedUser + "inside success");
var changeTo;
var deviceID;
console.log(current + "current");
for(var i = 0; i < obj.clients.length; i++)
{
if((selectedUser == obj.clients[i].userName) && (assigned == false))
{
console.log(selectedUser + " inside if");
current = JSON.stringify(obj.clients[i]);
changeTo = obj.clients[i].uri;
device = obj.clients[i].deviceID
assigned = true;
}
}
assigned = false;
console.log(current + " current");
console.log(previous + "previous");
if(previous !== current)
{
console.log("ARE WE INSIDE HERE");
$.ajax({
url: 'https://api.spotify.com/v1/me/player/play',
contentType: 'application/json',
type: 'PUT',
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + access_token
},
data: JSON.stringify({"uris":[changeTo], "device_id":device, "offset": { "uri":changeTo} }),
success: function(response) {
console.log(response);
}
});
}
}
});
previous = current;
console.log(selectedUser);
}, 2000);
}
else if($(this).hasClass('selected'))
{
$(this).toggleClass('selected');
console.log("not selected");
clearInterval(pollUser);
}
});
`
答案 0 :(得分:2)
var pollUser
是你期望setInterval的id是正确的吗?因为在函数的后面,你会pollUser = setInterval(function()...
。请参阅setInterval上的docs。
这不起作用,因为在click
.profTemp
pollUser
{{}}}上,您通过在函数顶部执行var pollUser
来创建新的.profTemp
变量。
如果您希望实际保存setInterval的ID,则应将其保存到a = 1
b = 1
单击处理函数范围之外的变量中,以便进行维护。
答案 1 :(得分:-1)
把var pollUser;在onclick功能之前。