Javascript Behaviour [duplicate] - javascript

This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 2 years ago.
I am trying to make a seconds countdown with Javascript.
Here is my HTML
<div id="ban_container" class="error center">Please wait
<span id="ban_countdown" style="font-weight:bold">
45</span>
seconds before trying again
</div>
And my JS:
<script type="text/javascript">
var seconds = <?php echo $user->getBlockExpiryRemaining(); ?>;
function countdown(element) {
var el = document.getElementById(element);
if (seconds === 0) {
document.getElementById("ban_container").innerHTML = "done";
return;
}
else {
el.innerHTML = seconds;
seconds--;
setTimeout(countdown(element), 1000);
}
}
countdown('ban_countdown');
</script>
However for some reason, it is not waiting the timeout time, but instead executes countdown right away so that when I refresh the page it just displays "done" right away. I know it is actually being executed multiple times because if I do innerHTML += seconds + " "; it counts down from 45. Why is the timeout being bypassed?

setTimeout(countdown(element), 1000); executes your function with that argument and passes the result into setTimeout. You don't want that.
Instead, execute an anonymous function that calls your function:
setTimeout(function() {
countdown(el); // You used `el`, not `element`?
}, 1000);

If you'd like to pass an argument to a function by setTimeout, try this:
setTimeout(countdown, 1000, element);
The syntax of setTimeout is the following:
setTimeout(function,milliseconds,param1,param2,...)

It is because setTimeout is asynchroneous. Try this:
setTimeout(function(){
countdown('ban_countdown'); //or elemement
}, 1000);
This will make the function countdown execute after 1000 miliseconds.

Related

How to put break delay after every 15 query execute

How do I put 5 minutes delay after submit every 15 Query
so this is the javascript code I am using and it works fine.
But what I want is:
I need to set a delay like of every 5 sec then execute the query, also after every 15 queries, needs to add a break for 5 minutes then continue the execution
<script>
$(function(){
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='http://i.imgur.com/pKopwXp.gif' alt='loading...' />";
// load() functions
var loadUrl = "xxx.com/api.php?phone=xxxx&body=xxx";
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
// end
});
</script>
setInterval function returns an id which can be used to clear the call from the interval function, after passing the id to the clearInterval function. You can try something like this where I call a function after clicking a button every 5 seconds and keeping a counter variable on how many times the variable was incremented. If the counter is 5 then clear the interval and call the interval function after 10 seconds. Script code is something like this:
$(function(){
$("#button").click(function() {
intervalCall()
})
});
function intervalCall() {
var counter = 0
var intervalId = setInterval(function() {
console.log("Hello")
counter++
if (counter == 5) {
clearInterval(intervalId)
setTimeout(intervalCall, 10000)
}
}, 5000)
}
JsFiddle code here.

How setTimeout function is working in this case? [duplicate]

This question already has answers here:
Recursive setTimeout in javascript
(2 answers)
Closed 5 years ago.
<body>
<input type="text" value="10" id="txtBox" /><br/><br/>
<input type="button" value="Start Timer" onclick="startTimer('txtBox')" />
<input type="button" value="Stop Timer" onclick="stopTimer()" />
<script type="text/javascript">
var intervalId;
function startTimer(controlId)
{
var control = document.getElementById(controlId);
var seconds = control.value;
seconds = seconds - 1;
if (seconds == 0)
{
control.value = "Done";
return;
}
else
{
control.value = seconds;
}
intervalId = setTimeout(function () { startTimer('txtBox'); }, 1000);
}
function stopTimer()
{
clearTimeout(intervalId);
}
</script>
</body>
I am new to JavaScript. I was going through some tutorial, the above code snippet I came across, which works completely fine for starting a countdown timer from 10 to 0 in every 1000 millisecond interval. I am confused that how setTimeout() is calling the function repeatedly, when it is supposed to call the function only once after waiting 1000 millisecond.
function startTimer(){...} is a named function. One advantage of named function is that it call itself from inside its body. The code you shared is exploiting this concept & the code inside setTimeout is calling the same function startTimer
intervalId = setTimeout(function() {
startTimer('txtBox');
}, 1000);
The startTimer() function will be called by the setTimeout() function. Then when the startTimer() function is executing, it will call the setTimeout() function again. So it is a lot like a loop.
You can also use setInterval instead:
intervalId = setInterval(function(){
startTimer('txtbox');
}, 1000);
use it outside the startTimer function. It will call the startTimer function once every 1000 milliseconds repeatedly.

How to kill interval function dynamically [duplicate]

This question already has answers here:
Stop setInterval
(6 answers)
Closed 5 years ago.
I am working on the snippet below. Is there a way to check whether the setInterval() is really killed or still running in background processing?
Technically what I need to do is killing the JS setInterval whenever the .map is not in the page. My understanding is the setInterval() still running every 2 second just is not writing on the console because of if statement.
setInterval(
function() {
if ($(".map")[0]) {
console.log("Map is in the Page");
} else {
//Stop Interval
}
}, 2000);
setTimeout(function(){ $(".box").empty();
}, 9000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div class="map">Map in Here</div>
</div>
You need to call clearInterval() to stop the execution of the intervalled function.
Here's an example:
let i = 3;
let interval = setInterval(function() {
if (i > 0) {
console.log("Running " + i--);
} else {
clearInterval(interval);
console.log("Stopped");
}
}, 2000);
In order to kill an interval or timeout you should assign it to a variable for referencing. The specific functions are: clearInterval(your interval reference variable name) and clearTimeout(your timeout reference variable name).
var yourInterval = setInterval(
function() {
console.log("Still running?"); //for testing purpose.
if ($(".map")[0]) {
console.log("Map is in the Page");
} else {
clearInterval(yourInterval); //it kills this interval, if the interval already terminated, it won't do anything harm, nor produce an error message in the browser console.
}
}, 2000);
setTimeout(function(){ $(".box").empty();
}, 9000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div class="map">Map in Here</div>
</div>

javascript runs twice [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have this code in my section:
function showIt() {
document.getElementById("hid").style.visibility = "visible";
}
setTimeout("showIt()", 6000); // 1000 = 1 sec
function showIt() {
document.getElementById("hid2").style.visibility = "visible";
}
setTimeout("showIt()", 7000); // 1000 = 1 sec
I am trying to reveal two separate elements. But the code always seems to work with only the first element.
This comes first on the page
<div id="hid2" style="visibility: hidden" class="video-arrow">
<p>Ready for some help growing your business?</p>
<div class="arrow-bg"><img src="img/arrow-bg.png" alt=""></div>
</div>
And This Comes Second
<div id="hid" style="visibility: hidden" class="header-button">
<div class="header-button-center">
<a href="">
<p class="offer">
<u>YES!</u>I Want To Get Instant Access To Interactive Offer!
<span>ยป</span></p>
</a>
</div>
<p class="guarantee">No worries. Our offer comes with a
<b>30-Day Money-Back Guarantee!</b></p>
</div>
Due to the nature of the div layout I can't put both elements in the same hidden div, and... ideally, I would display them at different times.
You cannot have two different functions with the same name. Try to change name the second function:
function showIt() {
document.getElementById("hid").style.visibility = "visible";
}
setTimeout(showIt, 6000); // 1000 = 1 sec
function showIt2 {
document.getElementById("hid2").style.visibility = "visible";
}
setTimeout(showIt2, 7000); // 1000 = 1 sec
you have defined showIt() function twice, its better if you create single function and pass element id as function parameter like
function showIt(id) {
document.getElementById(id).style.visibility = "visible";
}
You have two different functions with the same name in your code, It's not correct.
Try this:
function showIt1() {
document.getElementById("hid").style.visibility = "visible";
}
setTimeout(showIt1(), 6000); // 1000 = 1 sec
function showIt2() {
document.getElementById("hid2").style.visibility = "visible";
}
setTimeout(showIt2(), 7000); // 7000 = 7 sec
OR you can also try this one:
function showIt(Id) {
document.getElementById(Id).style.visibility = "visible";
}
setTimeout(showIt("hid"), 6000); // 1000 = 1 sec
setTimeout(showIt("hid2"), 7000); // 7000 = 7 sec
Use Like
function showIt1() {
document.getElementById("hid").style.visibility = "visible";
}
setTimeout("showIt1()", 6000); // 1000 = 1 sec
function showIt2() {
document.getElementById("hid2").style.visibility = "visible";
}
setTimeout("showIt2()", 7000); // 1000 = 1 sec
Pretend you are the web browser and read your code, s-l-o-w-l-y.
function showIt() {
document.getElementById("hid").style.visibility = "visible";
}
// cool, some code. This defines function showIt
setTimeout("showIt()", 6000); // 1000 = 1 sec
// a to do item. He sent me a string instead of a function, so in 6 seconds
// I will call eval on "showIt()";
function showIt() {
document.getElementById("hid2").style.visibility = "visible";
}
// hmm, he changes his mind. OK, now this is function showIt
setTimeout("showIt()", 7000); // 1000 = 1 sec
// another to do item. Another string.
// So in 7 seconds I will execute "showIt()" means by using eval().
// 6 seconds go by.
// Time to run "showIt()". Oh, its a function call.
// Use the latest version of showIt(), displaying hid2.
// ...
// another second goes by
// Time to run "showIt()". Same function we called a second ago.
// Make hid2 visible again. Oh, it already is. Oh, well.
Key points:
setTimeout doesn't wait. It is very fast. It sets up something to execute later.
When "showIt()" is executed, showIt() is the second version
It is better to give setTimeout a function than a string that calls a function, especially for cases where the function is only called once. You can use an anonymous function within the setTimeout parameter list.
setTimeout(
function(){ document.getElementById("hid").style.visibility = "visible"},
6000);
setTimeout(
function(){ document.getElementById("hid2").style.visibility = "visible"},
7000);
See also: MDN docs for window.setTimeout()
function showIt() {
setTimeout(function(){document.getElementById("hid").style.visibility = "visible";},6000);
setTimeout(function(){document.getElementById("hid2").style.visibility = "visible";},7000);
}
I think the reason is that you have 2 functions named showIt. The second showIt will overwrite the first one. You can try with different function names.
You can use the following:
function showAndTimeOut (id, time)
{
showIt(id);
setTimeout(function(){/* Dummy anonymous function! */}, time); // 1000 = 1 sec
// or may be you can use below line instead of above two:
setTimeout(showIt(id), time);
}
function showIt(id)
{
document.getElementById(id).style.visibility = "visible";
}
For calling you can use,
showAndTimeOut ("hid", 6000);
showAndTimeOut ("hid1", 7000);

setTimeout() is not waiting [duplicate]

This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 2 years ago.
I am trying to make a seconds countdown with Javascript.
Here is my HTML
<div id="ban_container" class="error center">Please wait
<span id="ban_countdown" style="font-weight:bold">
45</span>
seconds before trying again
</div>
And my JS:
<script type="text/javascript">
var seconds = <?php echo $user->getBlockExpiryRemaining(); ?>;
function countdown(element) {
var el = document.getElementById(element);
if (seconds === 0) {
document.getElementById("ban_container").innerHTML = "done";
return;
}
else {
el.innerHTML = seconds;
seconds--;
setTimeout(countdown(element), 1000);
}
}
countdown('ban_countdown');
</script>
However for some reason, it is not waiting the timeout time, but instead executes countdown right away so that when I refresh the page it just displays "done" right away. I know it is actually being executed multiple times because if I do innerHTML += seconds + " "; it counts down from 45. Why is the timeout being bypassed?
setTimeout(countdown(element), 1000); executes your function with that argument and passes the result into setTimeout. You don't want that.
Instead, execute an anonymous function that calls your function:
setTimeout(function() {
countdown(el); // You used `el`, not `element`?
}, 1000);
If you'd like to pass an argument to a function by setTimeout, try this:
setTimeout(countdown, 1000, element);
The syntax of setTimeout is the following:
setTimeout(function,milliseconds,param1,param2,...)
It is because setTimeout is asynchroneous. Try this:
setTimeout(function(){
countdown('ban_countdown'); //or elemement
}, 1000);
This will make the function countdown execute after 1000 miliseconds.

Categories

Resources