Hi i am using Javascript set timeout to run a certain function.
How do i display the last 10 seconds of the timeout when it is nearing the end?
var a = setTimeout('someFunction()', 10000);
Is it able to display something using the value that it store into the variable?
Thanks
I have created a small demo for you,
http://jsfiddle.net/praveen_prasad/DYaan/1/
<div id="target" style="display:none">
target
</div>
var target,
allotedTimeForWork=100 /*you can change this*/
;
var handler = setTimeout(function(){
if(!target)
{
target=document.getElementById('target');
}
target.style.display="block";
startTicker();
}, allotedTimeForWork);
function startTicker()
{
var counter=10;
var tickerHandler= window.setInterval(function(){
if(counter>0)
{
//cache target
target.innerHTML="you have "+counter +" seconds left";
counter--;
}
else
{
target.innerHTML="time over";
clearInterval(tickerHandler);
}
},1000);
}
It is not possible to directly get the remaining time of a Timeout.
You could either try to make multiple Timeouts for every second, or have another variable where you store when the Timeout was started.
I would use two timeouts.
The first with time minus 5 seconds, that calls a function with the second timeout (5 seconds) which would have the timer displayed.
Take a look here: http://jsfiddle.net/VCAnm/
HTML:
<span id="aaa">10</span>
JavaScript:
setInterval(function() {
var elem = document.getElementById('aaa');
elem.innerHTML = elem.innerHTML - 1;
}, 1000);
set 2 timers one for the timeout and another for the warning
var warn_time = 5000;
var function_name = 'someFunction()';
var a = setTimeout('warnFunction(function_name, warn_time)', 10000 - warn_time);
function warnFunction(function_name, time) {
alert('only ' + time + ' seconds left'); //use a div or whatever to display
var b = setTimeout(function_name, time);
}
Related
I am working on a piece of code that is supposed to randomly display a view count on my site. It all works fine, except that it only runs once on page load. Its supposed to change the view count every 10 seconds after the initial first run. E.g. run this code snippet every 10 seconds after page load. I have tried multiple ways with setInterval but found that it is supposedly bad practice to use anyways after so many failed attempts?
Could you guys point me in the right direction. I have been reading posts on Stack overflow for hours and none had an answer to my issue. I have a feeling, that I am overlooking something obvious here.
document.addEventListener('page:loaded', function() { //// Page has loaded and theme assets are ready
(function() {
var f = function() {
document.addEventListener('DOMContentLoaded', function() {
// Minimum view count
var minViews = 2;
// Maximum view count
var maxViews = 20;
// Text to show after the view count number
var text = 'people are viewing this product right now.';
// Create the new element to display on the page
$(".view-count").get().forEach(function(entry, index, array) {
var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews) + minViews) + ' ' + text;
$(entry).html($viewCountElement);
});
});
};
window.setInterval(f, 10000); //10 sec interval
f();
})();
});
You may not need nested event listener. You can just call the setInterval in the call back function of DOMContentLoaded.
function elementDisplay() {
// Minimum view count
var minViews = 2;
// Maximum view count
var maxViews = 20;
// Text to show after the view count number
var text = 'people are viewing this product right now.';
// Create the new element to display on the page
$(".view-count").get().forEach(function(entry, index, array) {
var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews) + minViews) + ' ' + text;
$(entry).html($viewCountElement);
});
}
document.addEventListener('DOMContentLoaded', function() {
window.setInterval(elementDisplay, 10000); //10 sec interval
});
setInterval is a browser based API, zo it should be cleaned up from the browser properly.
This is majorly for your proper implementation of setInterval. You can add your listeners, too.
FYI: jQuery.ready/DOMContentLoaded occurs when all of the HTML is ready to interact with, but often before its been rendered to the screen.
var interval;
$(document).ready(function(){
console.log("I am initialized")
var f = function() {
console.log("I am called")
// Minimum view count
var minViews = 2;
// Maximum view count
var maxViews = 20;
// Text to show after the view count number
var text = 'people are viewing this product right now.';
// Create the new element to display on the page
$(".view-count").get().forEach(function(entry, index, array) {
var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews) + minViews) + ' ' + text;
$(entry).html($viewCountElement);
});
};
interval = setInterval(f, 10000);
});
$(window).on("beforeunload", function() {
// clear the interval when window closes
return clearInterval(interval);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note: Check the console for output
i want to take out the result of the count up timer and show it on the page by clicking on button.
Here's my solution for your problem,
I just made a simple counter and then each time I trigger the click event it will show the current timer value
The code:
//initialisation
var counterLabel = document.getElementById("counter");
var valueLabel = document.getElementById("value");
var totalSeconds = 0;
counterLabel.innerHTML = totalSeconds;
//the loop each 1s
setInterval(setTime, 1000);
//the function that will increase the conter value and save it into the cookie
function setTime() {
++totalSeconds;
counterLabel.innerHTML = totalSeconds;
}
//to get the current conter value
function getTime() {
valueLabel.innerHTML = totalSeconds;
}
<label id="counter"></label>
<button onclick="getTime()">save</button>
<label id="value"></label>
Fiddle:
https://jsfiddle.net/871t3w2o/3/
You can also have a look into localstorage and sessionstorage they both work like the cookie but each one has it own advantages and disadvantages and you should choose the one that satisfy your need
I have a little problem with my code.
I have it setup so that by default, a rotating fadeIn fadeOut slider is auto playing, and when a user clicks on a li, it will jump to that 'slide' and pause the slider for x amount of time.
The problem i have is that if the user clicks on multiple li's very fast, then it will run color1() multiple times with will start colorInterval multiple times. This gives a undesired effect.
So what i need help with, is figuring out how to reset my code each time a li is clicked, so whenever ColorClick is clicked, i want to make sure that there are no other instances of colorInterval before i start a new one.
Thanks in advance!
=================================
edit:
I now have another problem, i believe that i fixed the clearInterval problem, but now if you look at var reset, you'll see that it runs color1() each time a li is clicked, which runs multiple intervals, so i need to delete the previous instance of color1() each time it is called, to make sure that it doesnt repeat any code inside multiple times. So when a li is clicked delete any instances of color1()
or
i need that instead of running color1 in var reset, i will go straight to colorInterval instead of running color1() for each li clicked,
so run colorInterval after x amount of time in var reset.
function color1() {
var pass = 0;
var counter = 2;
var animationSpeed = 500;
var $colorContent = '.color-container-1 .color-content-container'
var $li = '.color-container-1 .main-color-container li'
$($li).on('click', function() {
colorClick($(this));
});
function colorClick($this) {
var $getClass = $this.attr("class").split(' ');
var $whichNumber = $getClass[0].substr(-1);
var $Parent = '.color-container-1 ';
pass = 1;
$($colorContent).fadeOut(0);
$($colorContent + '-' + $whichNumber).fadeIn(animationSpeed);
var reset = setTimeout(function() {
clearTimeout(reset);
pass = 0;
color1();
}, 10000);
}
var colorInterval = setInterval(function() {
if (pass > 0) {
clearInterval(colorInterval);
return; //stop here so that it doesn't continue to execute below code
}
$($colorContent).fadeOut(0);
$(($colorContent + '-' + counter)).fadeIn(animationSpeed);
++counter
if (counter === $($colorContent).length + 1) {
counter = 1;
}
}, 7000);
}
You could just clear the interval inside of the click event.
var colorInterval;
$($li).on('click', function() {
clearInterval(colorInterval);
colorClick($(this));
});
//Your other code
colorInterval = setInterval(function() {
//Rest of your code
});
One thing play with is jQuery animations have a pseudo class selector :animated when animation is in progress
if(!$('.your-slide-class:animated').length){
// do next animation
}
I'm having this div element that shows the time past since it got created. However it doesn't get updated and always remains on few seconds ago. It looks like this
var newMsg= "<div id="chat-time">'+ moment().fromNow()+'</div>";
$("#chat-list").html( newMsg);
How can I update this text. I know I can do it with sentInterval but I can't figure out how to do it properly.It just prints out seconds! I'm using this for a chatroom. So each message will have a timestamp in the formatof momentjs.fromNow().
Does setting timer for all these message create a problem? I'd appreciate a hint.
EDIT:I'm using this code as mentioned in below but it's not showing anything:
<div id="chat-time"></div>
var messageTimeStamp = new Date();
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-time").html(time);
}, 1000);
To make this work you need the element in the dom and the setInterval running without being included in any string concatenation
HTML
<div id="chat-time"></div>
JS
var $chatTime = $('#chat-time').text(moment().fromNow());
setInterval(function(){
var time = moment().fromNow();
$chatTime.txt( time );
}, 1000);
UPDATE 2
Given that you're using socket.io, you'd do something like this (demo: http://plnkr.co/edit/QuaMV6x1vNB0kYPaU6i1?p=preview):
// The messages the user can currently see.
var messages = [];
// You have something like this in your code, presumably.
socket.on('new message', function(data) {
addChatMessage(data);
});
function addChatMessage(data) {
// First add the message to the dome, with a unique id for the timestamp text.
var messageElementId = 'chat-message-' + data.messageId;
$("#chat-list").prepend($("<div>" + data.message + "<i> (sent: <span id='" + messageElementId + "'>just now</span>)</i></div>"));
// When you no longer display that message in the DOM it from clear this array. I'd render the DOM based on this list if I were you.
messages.push({
messageElementId: messageElementId,
timestamp: data.timestamp
});
}
// By updating all the messages at once you don't have memory leaks.
setInterval(function() {
messages.forEach(function(message) {
var time = moment(message.timestamp).fromNow();
$("#" + message.messageElementId).text(time);
});
}, 1000);
UPDATE 1
Given this is your code:
var newMsg= "<div id="chat-time">'+ moment().fromNow()+'</div>";
$("#chat-list").html(newMsg);
You would do this, instead:
var messageTimeStamp = new Date(); // You need to grab this from somewhere.
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-list").html(time);
}, 1000);
You need to use moment(TIMESTAMP_OF_MESSAGE) not moment() and do something like this:
$(function(){
$("body").append($('<div id="chat-time"></div>'));
var messageTimeStamp = new Date();
var i = 0;
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-time").html('moment().from(messageTimeStamp): ' + time + '; setInterval calls made ' + i++);
}, 1000);
});
Here's a demo.
http://plnkr.co/edit/QuaMV6x1vNB0kYPaU6i1?p=preview
I dont see any problem using setInterval (). AngularJS wrapper setInterval on $interval service module . Check out these urls: interval Angular and Wrapper SetInterval
I found this JS-Countdown Script at JSFiddle.
EDIT:
I'm using the code of rafaelcastrocouto now, which is nearly perfect. I wanted a 10-seconds JQuery Countdown-Script with an interval that resets the countdown timer at 5 seconds and starts over again and again, but only for a specific class with a specific id on the whole HTML page. If it drops to 0, the countdown should stop. Also I want to reset specific counters to 10.
It's about a WebSocket that refreshes every second and depending on the data I get for specific counters I want to reset them or they should count down to zero.
New JSFiddle: http://jsfiddle.net/alexiovay/azkdry0w/4/
This is how I solved with jquery and native setInterval...
var setup = function(){
$('.count').each(eachSetup);
};
var eachSetup = function(){
var count = $(this);
var sec = count.data('seconds') ;
count.data('count', sec);
};
var everySecond = function(){
$('.count').each(eachCount);
};
var eachCount = function(){
var count = $(this);
var s = count.data('count');
count.text(s);
s--;
if(s < 0) {
s = count.data('seconds');
}
count.data('count', s);
};
setup();
setInterval(everySecond, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="count" data-seconds="5"></p>
<p class="count" data-seconds="10"></p>
<p class="count" data-seconds="15"></p>
You have sever errors in code, e.g.
setTimeout(cd_go(id), 1000); - should point to function reference not to function execution. setTimeout also returns the timeout id. You must past that id to clearTimeout
clearTimeout(this); it should take id instead of global object (window) or undefined if you are working in strict mode
loop = setInterval(function(id) { … } - id points to undefinded as you are not passing any value for it