'Running the same setInterval multiple times at once
I am putting together a personal overlay for my stream, using NodeJS sockets and a simple web page, and it has, for each chat message, the player's little character run across the bottom of the screen. So far, this has worked great, but I was trying to look into setting up this to be capable of the same character running across multiple times, mostly for the fun of it. The problem I came across is that when setting a new interval, the old one stops and the character gets frozen in place. I'm hoping to be able to get this to work and hope some help with a revision is available. :)
Here's the code
function animPlayer(name){
$.get(`/images/players/${name}strip.png`).done(function() {
//clearInterval(tID);
var tID;
var rID;
document.getElementById("playercontain").innerHTML += `<p id="image" class='${name}'> </p>`;
var elemy = document.getElementsByClassName(name);
var elem = elemy[elemy.length - 1];
var position = 69;
var rposition = -100;
const interval = 150;
elem.style.backgroundImage = `url('/images/players/${name}strip.png')`;
elem.style.right = '-100px';
rID = setInterval (() => {
elem.style.right = `${rposition}px`;
if(rposition < 2080){
rposition += 4;
} else {
elem.remove();
clearInterval(rID);
}
}, 2);
setTimeout(() => {
elem.style.right = '-100px';
}, 4000);
tID = setInterval (() => {
elem.style.backgroundPosition = `-${position}px 0px`;
if (position < 138) {
position = position + 69;
} else {
position = 0;
}
}, interval);
}).fail(function() {
console.log('it busy');
})
}
For explanation, the code checks for the existence of the player's sprite strip image, and if it exists, it adds the image to the page, then animates it through a JSFiddle interval, as well as shoots it across the screen with a simple style.right assignment, but as stated before, when the player chats again, the original freezes in place. I could have it check for the existence of the image and reset the position, but I personally would like to have multiple running across at once. Please help me, thank you. <3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
