I am new to JS.
I have 2 cards like the below,
<div class = "card" id ="c1">
<div class = "content"> </div>
</div>
<div class = "card" id ="c2">
<div class = "content"> </div>
</div>
The div content in the card 1 should display the dynamic value like Date.now() and the content in card2 should display the static Value.
JS:
function cardData(card) {
myCard(card);
}
function allCardData() {
var cards = document.getElementsByClassName("card");
Array.prototype.forEach.call(cards, (card) => {
cardData(card);
});
}
function mockData(card) {
var setInt;
function caseOne(card, callBackOne) {
callBackOne(card);
}
function caseTwo(card, callBackTwo) {
callBackTwo(card);
}
// SetInterval function
function callBackOne(card) {
setInt = setInterval(function () {
var currentDate = Date.now();
var val = String(currentDate).substr(8, 2);
}, 1000);
}
//clearInterval
function callBackTwo(card) {
clearInterval(setInt);
}
switch(card)
{
case "c1":
return {
target: card,
value: caseOne(card, callBackOne)
}
case "c2":
return {
target: card,
value: caseTwo(card, callBackTwo)
}
}
}
function Callback(value, callback) {
callback(value);
}
function myCard(card) {
Callback(mockData(card), function (data) {
console.log(data);
var target = document.getElementById(data.target);
var content = target.getElementsByClassName('content')[0];
content.innerHTML = data.value;
});
}
//Onload function
window.onload = function () {
allCardData();
};
I need a dynamic data every 2S in card1 and a static data Which clears the dynamic value in card2.
But, it is not working.
Since, callback function expects return, When I pass the function mockData to the callback. It is not working as expected.
Could someone please help me to start the dynamic data in card1 and clear the data in card2.?
Many thanks.
This is what the code does:
allCardData() for window.onloadallCardData() calls cardData() for each card found with the card's idcardData() calls myCard() in an intermediate stepmyCard() makes Callback call mockData() for the cardmockData() calls caseOne() for card c1 and caseTwo() for card c2caseOne() sets a 2 second intervalcaseTwo() cancels the intervalThere is no time between calling caseOne() and caseTwo(). They are called after each other with no time in between. This means the timer is cancelled immediately after it is initialized. No time for the 2 second timer to do anything.
Suggested solution to change caseTwo() to only clear timer after a certain condition has passed. Otherwise the interval will never start.
You may want to google about async/await, you may need to change your code in other parts:
async function caseTwo(card) {
// asynchronously wait, stopping this function until the value is known
var value = await getValueTwoFromSomewhere();
clearInterval(setInt);
return value;
}
Otherwise the code would need to be rewritten to something different.
Maybe you want to rethink your solution and post it again as another question.