Timer for individual <div> - javascript

I'm currently trying to set a timer for each div created, whereby each div has a background color of green or red depending on if there are detections in the webRTC video. Is there a way to assign a timer to the divs individually? Or maybe to only check for my own video? I've tried something like below, but it does not work when there are more than 1 people in the call, as "time" will be a global variable. I've also tried something like time = Math.ceil((time+1)/checkerBox.length) , but it does not seem to work too. Any pointers will be helpful
function checker(){
var time =0;
var timer = setInterval(function (){
for(var i=0;i<checkerBox.length;i++){
if(checkerBox[i].style.backgroundColor=="red"){
time = time + 1;
console.log("Box" + videoNum[i].innerHTML + " is not present for : " + checkerBox[i].innerHTML + " seconds");
}else{
time = 0;
}
//Exceed time
if(checkerBox[i].innerHTML == 30){
setTimeout(function(){
takeScreenshot(videoNum[i-1]);
}, 100);
time = 0;
}
checkerBox[i].innerHTML = time;
}
},1000)
}
Update : I ended up using arrays
var takenFrom;
var d = new Date();
let timeKeep = new Array(0,0,0,0,0,0,0,0,0,0,0);
let screenShots = new Array(0,0,0,0,0,0,0,0,0,0,0);
function checker(){
timer = setInterval(function (){
for(var i=0;i<=(checkerBox.length)-1;i++){
tableRow[i+1].cells[2].innerHTML = timeKeep[i]
tableRow[i+1].cells[3].innerHTML = screenShots[i]
if(flag[i].innerHTML=="0"){
checkerBoxFalse(checkerBox[i]);
timeKeep[i] = timeKeep[i] + 1;
console.log("Box" + videoNum[i].innerHTML + " is not present for : " + tableRow[i+1].cells[2].innerHTML + " seconds");
if(tableRow[i+1].cells[2].innerHTML == 10 ){
takenFrom = "Box" + videoNum[i].innerHTML + "minute" + d.getMinutes() + " room" + ROOM_ID
takeScreenshot(videoNum[i],takenFrom);
screenShots[i] = screenShots[i] + 1;
timeKeep[i] = 0;
}
} else if(flag[i].innerHTML== "1"){
checkerBoxTrue(checkerBox[i]);
timeKeep[i] = 0;
}
}
},1000)
}

Yes:
for (let div of divs) {
setInterval(function() {
//do something with div
}, 1000);
}
let is block scoped, so each setInterval will have its own div.

Related

trying to count the seconds while my users is with the mouse over an element

I am new in Javascript and I am trying to count the seconds while my users is with the mouse over an element.But I can`t get the interval to stop. Here is my code until now. Thanks
var seconds = 0;
var el = document.getElementById('ceva');
function incrementSeconds() {
seconds += 1;
el.innerText = "You have been here for " + seconds + " seconds.";
}
var x;
document.getElementById("ceva").onmouseenter = function() {var x =
setInterval(incrementSeconds, 1000)};
function mouseLeave() {
clearInterval(x`);
}
document.getElementById("ceva").onmouseleave = function() {mouseLeave()};
Just remove the "var" in the mouseenter function. Change it as below
document.getElementById("ceva").onmouseenter = function(){
x = setInterval(incrementSeconds, 1000)
};

JavaScript - Delay execution of certain javascript

I need help in delaying the execution of my javascript.(not making the javascript to execute right after the webpage is being loaded) I wish to execute the javascript only after 10s after the webpage is being loaded. How can I do that? This is the script.
<script>
var interval = 10000;
var current_index = -1;
var sales_feeds = [];
var showtime = 5000;
<?php $s = get_option('wc_feed_delay_between_popups_appear');
if (!$s) {
$s = 5000;
}
?>
function hide_prev_feed_notify(index)
{
if( sales_feeds.eq(current_index).length > 0 )
{
sales_feeds.eq(current_index).animate({bottom: '-90px'}, 500);
}
}
function show_live_feed_notify(index)
{
sales_feeds.eq(index).animate({bottom: '10px'}, 1000);
current_index = index;
}
function show_next_live_notify()
{
if( (current_index + 1) >= sales_feeds.length )
{
current_index = -1;
}
//add randomness
current_index = (Math.floor(Math.random() * (sales_feeds.length + 1))) - 1;;
if( window.console )
console.log('will show ' + (current_index+1));
show_live_feed_notify(current_index + 1);
setTimeout(function() { hide_prev_feed_notify(current_index + 1); }, showtime);
}
function stop_live_notify()
{
removeInterval(inverval);
}
function readCookie(name)
{
var nameEQ = escape(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++)
{
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
jQuery(function()
{
jQuery('.wc_feed_close_btn').click(function()
{
var days = 30;
var date = new Date();
date.setTime(date.getTime() + (days *24 *60 *60 *1000));
if(window.console)
console.log(date.toGMTString());
document.cookie = 'wc_feed_closed=true; expires=' + date.toGMTString() + ';';
jQuery('.live-sale-notify').css('display', 'none');
clearInterval(interval);
return false;
});
sales_feeds = jQuery('.live-sale-notify');
show_next_live_notify();
interval = setInterval(show_next_live_notify, (showtime + <?php print $s + 100; ?>));
});
</script>
Note: I want to delay the following execution.
function show_live_feed_notify(index)
{
sales_feeds.eq(index).animate({bottom: '10px'}, 1000);
current_index = index;
}
I tried inserting
var delay = 10000;
or
var interval = 10000;
none of them seem to work.
I also tried
setTimeout (function(); 3000);
it came out with uncaught syntax error.
Please Help me guys!
Note: I'm new to js/php coding...
Looking at your code, I think you should just remove the line
show_next_live_notify();
at the bottom of your script. It automatically executes everything right upon start instead of letting setInterval do its job
To delay the whole script, replace the last two lines in the jQuery call with something like this:
function startMe() {
interval = setInterval(show_next_live_notify, (showtime + <?php print $s + 100; ?>));
}
setTimeout(startMe, 10000);
You function name is show_live_feed_notify, and you tried to use setTimeout. Therefore I suggest you to try the following:
var delay = 10000; // 10 seconds
setTimeout(function() {
show_live_feed_notify(current_index + 1);
}, delay )

Timer that keeps counting when navigating away from page

I have a timer that counts down once a specific page is visited. I need this timer to keep counting even if someone goes to a different page, and maintain the time counted to display it on the screen when they return to the original page where it was triggered.
The code I have in place is
<script>
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
//check existing cookie
cook=getCookie("test9_cookie");
if(cook==""){
//cookie not found, so set seconds=60
var seconds = '<?php echo OFFERTIME ?>';
}else{
seconds = cook;
console.log(cook);
}
// init var
var timeout = 0;
// end init var
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
//store seconds to cookie
setCookie("test9_cookie",seconds,1); //here 1 is expiry days
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
timeout = 1;
sessionStorage.setItem('nothanks', 1);
document.getElementById('timed-over').style.display = "block";
$("#timed-over").delay(4800).fadeOut(300);
document.getElementById('timed-container').style.display = "none";
} else {
seconds--;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
//localStorage.removeItem('timedpid') //to delete localstorage during testing
function checktaken(){
if(timeout===1) {
//do nothing as expired
}else if(localStorage.getItem('timedpid')) {
var storedpid = localStorage.getItem('timedpid')
var currentpid =<?php echo json_encode($time_limited_pid); ?>;
if (storedpid !== currentpid) {
var showOffer = document.querySelector("#timed-container");
showOffer.style.display = "block";
}
}else if(sessionStorage.getItem('nothanks')) {
// do nothing as offer not wanted
}else{
var showOffer = document.querySelector("#timed-container");
showOffer.style.display = "block";
}
}
setInterval('checktaken()',1);
</script>
Is there any way to make the original code keep counting when the page the script is on is navigated away from?
If not, a solution would be to move part of the script to the header and have it only load when on a specific page. Doing this would mean having to pass a var from the script in the header, to a script in a different file. I'm not too clued up on javascript and haven't had any luck sharing variables across multiple pages before.
Stuff the start time into the cookie (or local storage, anything permanent) and use the difference between that start time and the current time for your timer.

Browser Bug showing time text on input

I am dealing with the following puzzle and I cannot understand why it is happening.
I have the following [I believe to be] equivalent pieces of javascript code, but one does not work as expected (notice the Console.Log):
Updates the UI a single time, then unexpectantly stops updating : http://jsfiddle.net/silentwarrior/1m0v6oj1/
jQuery(function () {
var isWorking = true;
if (isWorking) {
var timeEnd = 1431220406000; // generated from php
var timeNow = 1431210557000; // generated from php
var counter = 1;
var t = "";
setInterval(function () {
try {
var c = timeEnd - timeNow - counter;
console.log(c);
var d = new Date(c);
if (c <= 1) {
window.location.href = window.location.href;
return;
}
t = "";
if (d.getHours() > 0) {
t += d.getHours() + "h ";
}
if (d.getMinutes() > 0) {
t += d.getMinutes() + "m ";
}
t += d.getSeconds();
jQuery("#factory_start_prod").val("Working ... " + t + "s left");
counter = counter + 1;
} catch (e) {
}
}, 1000);
}
});
Updates the UI constantly as expected: http://jsfiddle.net/silentwarrior/n3gkum2e/
jQuery(function () {
var isWorking = true;
if (isWorking) {
var timeEnd = 1431220406000;
var timeNow = 1431210557000;
var counter = 1;
var t = "";
setInterval(function () {
try {
var c = timeEnd - Date.now();
console.log(c);
var d = new Date(c);
if (c <= 1) {
window.location.href = window.location.href;
return;
}
t = "";
if (d.getHours() > 0) {
t += d.getHours() + "h ";
}
if (d.getMinutes() > 0) {
t += d.getMinutes() + "m ";
}
t += d.getSeconds();
jQuery("#factory_start_prod").val("Working ... " + t + "s left");
counter = counter + 1;
} catch (e) {
}
}, 1000);
}
});
The only difference from each other is that, the one that works uses Date.now() to get the current timestamp, while the other one uses a pre-built time stamp.
Why would one example update the text in the input correctly while the other wouldn't?
PS: it is important to me to use generated timestamps instead of Date.now() in order to not depend on the users system when calculating the time left.
Your first example is working, however with each iteration you are only subtracting 1 from the timestamp value, which is equivalent to 1ms. Hence the value never appears to change unless you wait a really long time. You need to increment the counter by 1000 on each iteration for a second to be counted:
counter = counter + 1000;
Updated fiddle

How to create a toggle button in Jquery-mobile?

I want my button to change color if clicked but it seems not working in this JQuery-Mobile. and If its clicked it seems like it increases the time count speed i dont know why.
Any help please guys.
var seconds = 0;
var minutes = 0;
var timer = null;
function toggle(ths) {
var clicked = $(ths).val();
$(ths).toggleClass("btnColor");
$("#tb").toggleClass("btnColorR");
$("#lblType").html(clicked);
$("#setCount").html(" minutes : " + minutes + " seconds : " + seconds);
//duration time
seconds = seconds + 1;
if (seconds % 60 == 0) {
minutes += 1;
seconds = 0;
}
timer = timer = setTimeout("toggle()", 1000);
}
try :
timer=setTimeout(function(){
toogle();
},1000);

Categories