javascript setTimeout not working inside if statement - javascript

I'm writing a code to alert the user inactive when the user is idle for some time.
setIdleTimeout = () => {
var timeout = 0;
timeout = setTimeout(onExpires, 500);
//Expires Function
function onExpires() {
timeout = 0;
alert('Timed out');
}
//This function executes on each mouse move.
function onMouseActivity(event) {
clearTimeout(timeout);
timeout = setTimeout(onExpires, 500);
}
}
The above code works fine. But when ever I add a condition to the clearTimeout, Its not working.
example:
//This function executes on each mouse move.
function onMouseActivity(event) {
var mouseSeconds =5
if(mouseSeconds < 10) {
//Now this is not working.
clearTimeout(timeout);
}
timeout = setTimeout(onExpires, 500);
}
Please help me out. This is driving me crazy for hours now.
Thanks.

you wrote
var mouseSeconds =5
if(mouseSeconds > 10) {
//Now this is not working.
clearTimeout(timeout);
}
mouseSeconds is 5 it will never be bigger then 10 :) so the statement is always false.

Related

Javascript Countdown Timer w/ Bootstrap Modal Pause

See my code below, I am trying to get the countdown timer to pause when a bs.modal is shown and to resume again once the modal is hidden. This works perfectly if the modal is opened and then closed but if you try to reopen the modal again, the timer just continues. I am probably missing something obvious but am not the best when it comes to JS.
(function countdown(remaining) {
if(remaining === 0) {
location.reload(true);
}
document.getElementById('countdown').innerHTML = remaining;
$(document).on('shown.bs.modal', function(e) {
console.log("modal triggered");
clearTimeout(timeout);
});
$(document).on('hide.bs.modal', function(e) {
console.log("modal closed");
countdown(remaining - 1);
});
timeout = setTimeout(function(){
if(remaining != 0) {
countdown(remaining - 1);
}
}, 1000);
})(300);
It seems the issue with the existing code is a timing problem that results in multiple timeouts getting set simultaneously, some of which can then never be cleared because their id's get lost. It's easy to get into such a situation when you're setting up a new timeout for every iteration. So, as I mentioned, setInterval() is a better choice here. Below is a solution using setInterval(). Also note that it's written so as to ensure that any existing interval is cleared before its id is overwritten (in the function clearAndSetInterval.)
(function (remaining) {
var interval;
var clearAndSetInterval = function () {
clearInterval(interval);
interval = setInterval(function (){
if (remaining <= 0) {
clearInterval(interval);
location.reload(true);
}
document.getElementById('countdown').innerHTML = remaining;
remaining = remaining - 1;
}, 1000);
};
$(document).on('shown.bs.modal', function(e) {
clearInterval(interval);
});
$(document).on('hide.bs.modal', function (e) {
clearAndSetInterval();
});
clearAndSetInterval();
})(300);

js setTimeout() finishes instantly without any rest

when coding, I came upon this very weird problem. My code is below:
js
document.getElementById("id").style.width = "0%"
var a = 0;
setTimeout(function () {
if (a <= 60) {
document.getElementById("id").style.width = a + "%";
a++;
}
}, 100);
I want it to run 60 times, each time changing the div's width by 1%
However, when I run the code, the if block makes it finish instantly as if the timeout didn't work. Can anyone tell me what's wrong? Thanks in advance!
setTimeout function executes only once after that specified time in milli seconds.
If you want to keep on executing the block, you have to make use of setInterval instead of setTimeout.
setInterval keeps on calling the function since the interval is cleared.
Dont forget to call clearInterval once target achieved.
var a = 0;
const interval = setInterval(function () {
if (a <= 60) {
console.log("Im being called");
document.getElementById("id").style.width = a + "%";
a++;
} else {
// Target achieved, clearing interval
console.log("Im stoping execution");
clearInterval(interval)
}
}, 100);
#id {
height: 300px;
background: orange;
}
<div id="id"></div>

Change background images using setTimeout

I have 31 images and I want to display them one after another as the background of a div. I only want it to change when the user hovers over the div. My problem right now is that it just flips through all the images really fast. I am attempting to use setTimeout, but it isn't working. How can I make the delay work?
The name of the div is About_Me_Block and the images are called frame1.gif,frame2.gif ...etc
Here is my code:
function changeImg(counter) {
$('#About_Me_Block').attr("style", "background-image: url(playGif/frame" + counter + ".gif);");
}
$(document).ready(function() {
var hoverAnimate = []
"use strict";
$('#About_Me_Block').mouseenter(function() {
hoverAnimate[0] = true;
var counter = 0;
while (hoverAnimate[0]) {
console.log(counter);
setTimeout(changeImg(counter), 1000);
counter++;
if (counter === 32)
hoverAnimate[0] = false;
}
});
$('#About_Me_Block').mouseleave(function() {
hoverAnimate[0] = false;
$(this).attr("style", "background-image: url(play.jpeg);");
});
});
setTimeout doesn't wait for the function to end, it works lile threading in other languages.
To achieve a what you want, you need to call setTimeout from the changeImg function.
var counter = 0;
$(document).ready(function() {
var hoverAnimate = []
"use strict";
$('#About_Me_Block').mouseenter(function() {
hoverAnimate[0] = true;
counter = 0;
changeImg();
});
$('#About_Me_Block').mouseleave(function() {
hoverAnimate[0] = false;
$(this).attr("style", "background-image: url(play.jpeg);");
});
});
function changeImg() {
$('#About_Me_Block').attr("style", "background-image: url(playGif/frame" + counter + ".gif);");
counter++;
if (counter < 32 && hoverAnimate[0]) {
setTimeout(changeImg, 1000);
} else {
hoverAnimate[0] = false;
}
}
the reason they happen all at once is because while statement doesn't have delay, so all setTimeout will be set up at the same time, thus, calling changeImg all at once.
To solve this problem, you can replace setTimeout with setInterval. Instead of using while, you can just call setInterval like
var counter = 0;
var myTimer = setInterval(changeImg, 1000);
and update counter inside changeImg every time it gets called. After looping, don't forget to
clearInterval(myTimer)
It seems you need to read up on how setTimeout works. It essentially places a reminder to run a function after a given amount of milliseconds have passed. So, when you do setTimeout(changImg(counter), 1000) you are calling changImg(counter) which returns undefined. Therein producing this setTimeout(undefined, 1000) which is why it flips really fast.
So, you can use bind to allow the function to be called later with that parameter built in. Also, make sure you remove the reminders once done with clearTimeout.
function changeImg(counter) {
$('#About_Me_Block').attr("style", "background-image: url(playGif/frame" + counter + ".gif);");
}
$(document).ready(function() {
var hoverAnimate = false, id;
function loop(counter) {
if(hoverAnimate || counter < 32) {
changeImg(counter);
id = setTimeout(loop.bind(this, counter++), 1000);
}
}
$('#About_Me_Block').mouseenter(function() {
hoverAnimate = true;
id = setTimeout(loop.bind(this, 0), 1000);
});
$('#About_Me_Block').mouseleave(function() {
hoverAnimate = false;
// Don't want a reminder for a random counter to wake up.
clearTimeout(id);
$(this).attr("style", "background-image: url(play.jpeg);");
});
});
Two methods for timers - setTimeout and SetInterval (single / repeating)
// setInterval is also in milliseconds
var intervalHandle = setInterval(<yourFuncToChangeImage>,5000);
//this handle loop and make example loop stop
yourelement.yourEvent = function() {
clearInterval(intervalHandle);
};

Javascript Countdown that loads ahref

I'm totally a beginner with JavaScript and I'm trying to make a Javascript Countdown that loads an
I'm using this code for the countdown
<script language="Javascript">
var countdown;
var countdown_number;
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
if(countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
if(countdown_number > 0) {
countdown = setTimeout('countdown_trigger()', 1000);
}
}
}
function countdown_clear() {
clearTimeout(countdown);
}
</script>
I want to load exactly this after the count reaches 0... I am totally lost... what should I do?
It is basically a countdown that stops a music player after reaching 0. I would like to set up several countdowns with 10 mins, 15 mins, and 30 mins.
var countdown;
var countdown_number;
function countdown_init(time) {
countdown_number = time;
countdown_trigger();
}
function countdown_trigger() {
if (countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
setTimeout('countdown_trigger()', 1000)
} else { // when reach 0sec
stop_music()
}
}
function stop_music(){
window.location.href = "bgplayer-stop://"; //will redirect you automatically
}
Here is a simple example using mostly what you had above. This will need to be expanded a bit in order to have multiple countdowns but the general idea is here.
Fiddle: http://jsfiddle.net/zp6nfc9b/5/
HTML:
<a id="link_to_click" href="bgplayer-stop://">link</a>
<span id="countdown_text"></span>
JS:
var countdown_number;
var countdown_text = document.getElementById('countdown_text');
var link_to_click = document.getElementById('link_to_click');
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
countdown_number--;
countdown_text.innerHTML = countdown_number;
if (countdown_number > 0) {
setTimeout(
function () {
countdown_trigger();
}, 1000
);
}
else {
link_to_click.click();
}
}
link_to_click.addEventListener('click',
function () {
countdown_text.innerHTML = 'link was clicked after countdown';
}
);
countdown_init();
To explain some portions a little I think overall you had the correct idea.
I only added the eventListener so you could see the link was actually being clicked and displays a message in the countdown_text for you.
You didn't need to check countdown_number more than once so I removed that if block.
Also you don't really need to clear the timeout either. It clears itself once it executes. You only really need to clear a timeout if you want to stop it before it completes but since we rely on the timeout completing in order to do the next step its not necessary.

Jquery setTimeout inside a setTimeinterval not working

I have a setinterval that moves bulldozer from the right to the left.
In the jsfiddle below, the setInterval must stop itself after 5 seconds. (used a settimeout and clearinterval for that) but it's not working. Can anyone help me?
http://jsfiddle.net/B5MKj/11/
var gameover;
gameover = setInterval(function () {
setTimeout(function () {
clearInterval(movingbulldozer);
}, 55000);
}, 10);
You had a typo in your fiddle, updated fiddle, if works just fine, but instead of 5000 ms you had 55000ms set for the timeout.
setTimeout(function () {
clearInterval(movingbulldozer);
}, 5000);
In your example, movingbulldozer is undefined. If you're trying to clear the interval, clear the interval with the right reference. In your example, this would be clearInterval(gameover);
The problem with your example is that every 10 ms you're adding a timeout to the DOM which clears the interval.
var timeout, interval, date,
i = 0;
$(document).ready(function() {
interval = setInterval(function() {
date = new Date();
i++;
$('#debug').html('Interval parsed at '+date.getTime()+', interval #'+i);
if (i >= 100) { // According to your example
$('#debug').html('Starting timeout...');
timeout = setTimeout(function() {
$('#debug').html('Timed out');
}, 5000);
clearInterval(interval);
}
}, 10);
});
Check out my example, see if it helps. :)
http://jsfiddle.net/faqq5/

Categories