How do I cause an animation every 5 seconds using jQuery? - javascript

Okay so I don't have much experience with jQuery. What I'm trying to do here is make the background of the page change every 5 seconds (10 seconds actually but 5 is for testing). Along with this I want a countdown animation, like a bar below on the page. I've got the background changing every 5 seconds but I cant get the bar animations working. It only occurs once or twice but then never happens again :////
this is the code for the bar animation
var initialWidth = 0;
var initialHeight = 0;
var firstMeasurements = function(){
initialHeight = $(".countdown").height() + "px";
initialWidth = $(".countdown").width() + "px";
}
$(function(){
var bar = $(".countdown");
function countdown() {
bar.animate({"width":"0px"}, 5000);
}
function restartCountdown() {
bar.css("width", initialWidth);
countdown();
setTimeout(restartCountdown, 5000);
}
bar.css("height", initialHeight);
restartCountdown();
});
"countdown" is the class of the div that I want to animate every 5 seconds.
Can someone please tell me what is wrong with my code?
thank you.

Here is the complete code LIVE DEMO
$(function () {
var firstMeasurements = {
width: $("#countdown").css('width'),
height: $("#countdown").css('width')
}
var startAnim = function () {
$("#countdown").animate({
"width": "0px", "height": "0px"
}, 5000, resetAnim)
}
var resetAnim = function () {
$("#countdown").css({
"width": firstMeasurements.width,
"height": firstMeasurements.height
});
startAnim();
}
startAnim()
});

Here you go... This should be enough to get you started :)
var time = 3000, //3 seconds
var timer = setInterval(function(){
alert("Hello");
}, time);
//Why declare the interval as timer var?
//Because you may wish to cancel it at some point by doing
//clearInterval(timer);

Instead of :
setTimeout(restartCountdown, 5000);
You should use:
setInterval(restartCountdown, 5000);
Because setTimeOut() will fire only once, but setInterval() will always fire every 5 seconds.
Note:
In your case you are calling restartCountDown() recursively, so if you will use setInterval() you need to change your function to the following:
function restartCountdown() {
bar.css("width", initialWidth);
setInterval(countdown, 5000);
}
This way you will initialize the width then fire countdown() after 5 seconds.

Ohoh. The Every-N-seconds question ;)
Actually today you only can use `setTimeInterval``
setInterval(function(){
console.log("5 secs have passed");
}, 5000/*5000 ms=5 seconds*/);
But care ! your Javascript can do nothing else during the setInterval.
Browser javascript runs in a single thread. So if you perform something that takes too long - it will freeze browser.
Future of Javascript will bring multi-thread.
To be able to do things during you wait 5 seconds, I have used strategies like asynchronous request. Well, fell free to ask if you dont want to be frozen during the 5 secs.
Some reads ? http://ejohn.org/blog/how-javascript-timers-work/

Related

Boolean statement not evaluating in javascript

I'm writing a script, and there are two boolean statements that are very similar but giving different results, and I don't see why they conflict with one another.
My function looks like this:
SCRIPT:
(function() {
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
if (stopped) {
setInterval(function() {
console.log("The timer is working.");
}, 1000);
}
button.addEventListener('click', function(){
if (stopped) {
stopped = false;
console.log(stopped);
} else {
stopped = true;
console.log(stopped);
}
});
}
}
}).call(this);
The basic idea is that when I push the button the setInterval function stops, however it keeps on going even when the if/else function switches stopped to false.
For example, my console.log looks like this:
I.e. stopped = false, but setInterval doesn't terminate.
Why is this not evaluating correctly?
The problem with your code is that you are trying to work on a piece of code that has already started to operate. In simpler words, the setInterval method will be called every 1000ms, no matter what the value of stopped variable is. If you wish to really stop the log, you can do any of these:
clearInterval()
to completely remove the interval or
setInterval(function() {
if (stopped) {
console.log("The timer is working.");
}
}, 1000);
to check if the value of stopped variable has changed or not (after the click) and act accordingly. Choose either of these for your purpose..
you are calling setinterval even before button is clicked .As the event is already triggered you cannot stop just by setting the variable to false ,you need to clear the interval using clearinterval
check the following snippet
var intervalId;
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
var Interval_id;
button.addEventListener('click', function() {
if (stopped) {
Interval_id = callTimeout();
stopped = false;
} else {
clearInterval(Interval_id);
stopped = true;
}
});
}
function callTimeout() {
intervalId = setInterval(function() {
console.log("The timer is working.");
}, 1000);
return intervalId;
}
<input type="button" id="start-stop" value="click it">
Hope it helps
Put the if(stopped) statement inside the setInterval function because if you used this function once it will keep going..
Another way to stop setInterval function is by using clearInterval, like this
var intervalId = setInterval(function() { /* code here */}, 1000)
// And whenever you want to stop it
clearInterval(intervalId);
When you click the button stopped variable becomes false but the setInterval will not stop because the setInterval code is already executed.. it will not execute again on button click. And if you reload the page what will happen is that stopped variable will be again set to true as you have written at first line and setInterval will execute again ..
Now What you can do is store setInterval in a variable like this
var timer = setInterval(function,1000);
and then when you click the button use this method to clear interval
clearInterval(timer);
this should do the trick .. Hope it helps ..

Javascript countdown timer is erratic

I have a raspberry pi that initiates a garage door close event after a 90s delay. I have been successful in showing the countdown timer dynamically update on a web page but for some reason the countdown is erratic and constantly flickers with lower and then higher numbers.
Clearly I must be refreshing something but needless to say I have spent many hours on forums but to no avail. I am hoping that someone can look at my code and give me some direction.
<?php
$pinInput = trim(shell_exec("gpio read 26"));
$pinOutput = trim(shell_exec("gpio read 2"));
if ($pinInput!=$pinOutput){
echo "Timing for auto reclose...";
?>
<br>
<b><span id="countdown">90</span> Seconds</b>
<script type="text/javascript">
var timer = 90,
el = document.getElementById('countdown');
(function t_minus() {
'use strict';
el.innerHTML = timer--;
if (timer >= 0) {
setTimeout(function () {
t_minus();
}, 1000);
} else {
// do stuff, countdown has finished.
}
}());
</script>
<?php
}
elseif ($pinInput=1)
{
echo "Monitoring input...";
}
else
{
echo "Garage door is closing...";
}
?>
I should also mentioned that the above piece of code is within a file called timing.php. This is called on index.php as follows:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#Input').load('timing.php');
}, 1000); // refresh every 1000 milliseconds
</script>
So in summary, what I would like is for "Timing for auto recluse..." to remain static if ($pinInput!=$pinOutput) but dynamically shown the countdown from 90s.
First let's look at this code, the last bit in your question:
var auto_refresh = setInterval(
function () {
$('#Input').load('timing.php');
}, 1000); // refresh every 1000 milliseconds
That sets up an interval timer that will load the "timing.php" URL into the page once per second.
Now, here's part of what you say is returned from "timing.php":
var timer = 90,
el = document.getElementById('countdown');
(function t_minus() {
'use strict';
el.innerHTML = timer--;
if (timer >= 0) {
setTimeout(function () {
t_minus();
}, 1000);
} else {
// do stuff, countdown has finished.
}
}());
So when the browser receives the response from "timer.php", jQuery will run that code. That sets up a repeating timer function — essentially the same thing as an interval timer, except that it stops itself after a while).
Now, when that code is reloaded, you don't get new global variables timer and el. The global variables already defined by the last load of "timer.php" will simply have their values overridden. That means that the already-in-process previous timeout sequence will suddenly see timer set back to 90.
It's not clear exactly what it is you intend to do. Perhaps that setInterval() is just superfluous, and all you need to do is just load "timeout.php" once. Or, perhaps when the "timeout.php" code loads, it first needs to wipe out any already-running timeout loops, though that seems odd since those are set up to wind down only after 90 seconds.

How to make a warning to user when 10 secs. to refresh setInterval?

I am using setInterval to refresh a content of graph in page. How to make a show an alert to user when setinterval is about to refresh that 'the content will be refreshed'.
For example my interval is using 300 secs and I want to show an alert after 290 seconds have passed that 'The content will be refreshed after 10 secs. Do you want to refresh the graph' for each interval. How to do this? Any suggestions?
You should set you interval to 290000ms, and then it will show an alert, and then you use setTimeout to update your page after 10 seconds, like so:
setInterval(function() {
alert("10 seconds to update")
setTimeout(function() {
//REFRESH PAGE
},5000);
}, 10000);
On your page loading you can put your 290 secs refresh
setInterval(function(){
showDialogBox("do you want to refresh");
}, 290000);
and then add a action on the confirm button that will be delayed the last 10sec
confirmButtonOnClick(){
setInterval(function(){
refresh();
}, 10000);
}
In cases like this, I prefer to use setTimeout over setInterval as it gives better control.
So I set two timers -- one for the warning and then another for the timeout itself, then I restart the two timers.
const timeoutWarning = 1800;
const timeoutDone = 2000;
function showWarning() {
console.log('About to time out...');
}
function doTimeout() {
console.log('Timeout reached');
setWarnings();
}
function setWarnings() {
setTimeout(showWarning, timeoutWarning);
setTimeout(doTimeout, timeoutDone);
}
setWarnings();
Something like that:
var interval;
var secondsPassed = 0;
function refreshWithMessage() {
interval = setInterval(function(){
if(secondsPassed == 290) {
//showMessage with options
}
if(secondsPassed == 300) {
clearInterval(interval);
//do what you need here (refresh page?)
}
secondsPassed++;
}, 1000)
}
If you need to let user cancel the interval - you should just clear interval and then reset seconds variable to 0.

how can I rearrange this code so my setInterval stops looping infinitely?

I'm trying to make a simple flip-card/memory match (like from super mario brothers 3) game in HTML/Javascript and am having a slight issue with the setInterval command.
Here is a link to the full code: http://jsfiddle.net/msfZj/
Here is the main issue/main logic of it:
if(click == 2) //denotes two cards being clicked
{
if(flippedArray[1].src === flippedArray[0].src) // if click 1 == click 2 then refer to function 'delayMatch' which sets click 1 and 2 cards to not be displayed
{
window.setInterval(function() { delayMatch() }, 500);
console.log("EQUAL");
}
else
{
window.setInterval(function() { delayNoMatch() }, 500); // if click 1 != click 2 then display card.png
console.log("NOT EQUAL");
}
function delayMatch() //function for matching pairs
{
flippedArray[0].style = "display:none;";
flippedArray[1].style = "display:none;";
}
function delayNoMatch() //function for non-matching pairs
{
flippedArray[0].src = "card.png";
flippedArray[1].src = "card.png";
}
click = 0; // when clicked two cards set click back to zero
}
The first two cards I click on always work: but from that point onward the setInterval keeps running the function over and over again in an endless loop every 500ms.
I'd be extremely appreciative if anybody can point my in the right direction on how I can do this properly.
Thank you very much for your time.
It looks like you need setTimeout, which only runs once?
window.setTimeout(function() { delayMatch() }, 500);
Otherwise, you need to clear the interval with clearInterval(i), but first set "i" using the return value of setInterval:
var i = window.setInterval(function() { delayMatch() }, 500);
Here's a demo (I JQuerified it a bit for JSFiddle).
You're going to want to go with setTimeout() instead of setInterval()
A handy function when you use setTimeout is clearTimeout. Say you want to set a timer, but maybe want a button to cancel
var timer = setTimeout(fn,1000);
//later maybe
clearTimeout(timer);

function is looped according to setinterval but with different parameters

i have a simple question, there is a function with parameter emp_id that opens up a form for a chat with different attributes, i want it to be refreshed automatically each 10 sec, now it works a bit wrongly, since there is a parameter emp_id that is can be changed, and once i change it, the chat with messages and form are refreshed double time or triple times :) depend on how many times u change the emp_id, i hope i was clear )) anyway here is the javascript function:
function load_chat(emp_id) {
var url = "#request.self#?fuseaction=objects2.popup_list_chatform"
url = url + "&employee_id=" + emp_id;
document.getElementById('form_div').style.display = 'block'; AjaxPageLoad(url,'form_div',1,'Yükleniyor');
setInterval( function() {
load_chat(emp_id);
},10000);
}
there a list of names, once i click on one of them, this form is opened by this function, but if i click another user, i mean if i change the emp_id, it refreshes, the previous and present form. how do i change it so that it will refresh only the last emp_id, but not all of id's which i've changed
thank you all for the help, i really appreciate it!
This would nicely encapsulate what you're doing. The timer id (tid) is kept inside the closure, so when you call load_chat it will stop the interval if there was one running.
Once the new url is set up, it will start the interval timer again.
var ChatModule = (function() {
var tid,
url;
function refresh()
{
AjaxPageLoad(url, 'form_div', 1, 'Yükleniyor');
}
return {
load_chat: function(emp_id) {
if (tid) {
clearInterval(tid);
}
// setup url
url = "#request.self#?fuseaction=objects2.popup_list_chatform"
url = url + "&employee_id=" + emp_id;
document.getElementById('form_div').style.display = 'block';
// load ajax
refresh();
// set timer
tid = setInterval(refresh, 10000);
}
}
}());
ChatModule.load_chat(123);
Use setTimeout instead. Each time your function is executed, it will set up the next execution (you could also make it conditional):
function load_chat(emp_id) {
... // do something
if (condition_still_met)
setTimeout(function() {
load_chat(emp_id); // with same id
}, 10000);
}
load_chat("x"); // to start
Or you will have to use setInterval outside the load_chat function. You can clear the interval when necessary.
function get_chat_loader(emp_id) {
return function() {
... // do something
};
}
var id = setInterval(get_chat_loader("x"), 10000); // start
// then, somewhen later:
clearInterval(id);

Categories