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.
Related
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.
I am looking for a way to call a function that should wait for 1000 miliseconds before executing. And when the function is called again before the 1000 miliseconds are reached, the timer should restart. So that the function runs 1000 miliseconds after the last time it was called.
So let's say I have a button:
<button type="button" id="btnclick">Click Me!</button>
And I want to display an alert after exactly 1000 miliseconds after the last time it was clicked. But when the button is clicked a second time, before the 1000 miliseconds have past, then the timer should restart.
If someone clicks the button 1 time, then the alert displays 1 second after the click.
If someone clicks the button, and then clicks again after 999 miliseconds, and then again after again 999 miliseconds, then I want to run the function 1 second after the last click (so 2,98 seconds after the first click).
Is this possible? And how?
My Best guess would be something like:
function delay(callback, ms) {
var timer = 0;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
$('#btnclick').click(function(e){
console.log('I want to see this everytime the button is clicked, without any delay');
delay(waitFunction(),1000);
});
function waitFunction(){
console.log('I want to see this 1 second after the LAST click');
}
(inspiration from: Wait for function till user stops typing )
Yes it is possible. you just have to check if an timeout is already counting down and, if it is, reset it. Here is a simple example.
// set timer-variable
var timer = null;
//on button-click
$('#btnclick').click (function (e) {
//clear timeout if already applied
if (timer) {
clearTimeout (timer);
timer = null;
}
//set new timeout
timer = setTimeout (function () {
//call wait-function and clear timeout
waitFunction ();
clearTimeout (timer);
timer = null;
}, 1000);
});
function waitFunction () {
console.log ('I want to see this 1 second after the LAST click');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btnclick">Click Me!</button>
I used lastclick variable to store date user clicked.
I defined lastclickworked variable to avoid double setTimeout calls. In settimeout function, i checked if 1 second passed, run the code. if 1 second doesn't passed then call settimeout again with 1 seconds- passed time
var lastclick=null;
var lastclickworked=true;
function clickMe(){
lastclick=new Date();
if(lastclickworked)
runcallback(1000);
}
function runcallback(milliseconds){
lastclickworked=false;
setTimeout(function(){
var current = new Date();
var milliseconds = (current.getTime() - lastclick.getTime());
if(milliseconds<1000){
runcallback(1000-milliseconds);
}else{
lastclickworked=true;
console.log('you clicked 1 second ago');
}
},milliseconds);
}
<button onclick="clickMe();">Click Me!</button>
It's a follow up to this question - https://stackoverflow.com/a/33430608/3766930
Basically I have a text area and when user starts typing in sth, the counter starts going down from 3 to 0. when it reaches 0 it gets disabled.
Now I want to add a feature of starting over - when user clicks the link start over, text area goes enabled again and user has 3 seconds (again) to perform the input.
I modified the jquery script:
$('#textArea').on('input propertychange', display30Seconds);
var interval;
function display30Seconds() {
var validTime = 3000;
if (!interval)
interval = setInterval(function () {
$('#counter').html(validTime / 1000);
validTime = validTime - 1000;
if (validTime < 0) {
clearInterval(interval);
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$('#counterIsDone').on('click', function(){
$('#textArea').prop('disabled', false);
display30Seconds();
});
}
}, 1000);
}
but I see that I cannot call the method display30Seconds(); again. Or rather I can, but the interval is not set again. How can I fix it?
Seems like I'm not entering the code inside
if (!interval)
because the interval is not visible any more after clearing it (?). So I thought about moving the var interval; into the body of the method function display30Seconds() {, but that doesn't bring the expected effect. Is there a way of fixing it?
Here is my updated fiddle: http://jsfiddle.net/jf4ea4nx/3/
Set interval=null after the clearInterval() call.
What seems to confuse you is the semantics of clearInterval(interval). As Patrick Evans points out in his comment, it will not set interval to a value that evaluates to false in a condition.
To make it completely clear you could use a boolean variable such as countdownRunning in addition to the interval variable to keep track of whether the countdown is active or not.
Try this:
$('#textArea').on('input propertychange', display30Seconds);
var interval=false;
function display30Seconds() {
var validTime = 3000;
if (!interval)
interval = setInterval(function () {
$('#counter').html(validTime / 1000);
validTime = validTime - 1000;
if (validTime < 0) {
clearInterval(interval);
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$(document).on('click','#counterIsDone', function(){
$('#textArea').prop('disabled', false);
display30Seconds();
});
interval=false;
}
}, 1000);
}
You can improve your code by using a conditional recursive call to to your iterative function instead - each call has a one second delay, which makes it slightly more intuitive to use (think of each call as one tick):
var seconds = 3;
$('#textArea').on('input propertychange', setTimeout(timeout.bind(null, seconds), 1000));
function timeout (iterations) {
$('#counter').html(iterations);
if (iterations === 0) {
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$('#counterIsDone').on('click', function(){
$('#textArea').prop('disabled', false);
timeout(seconds);
});
}
else {
setTimeout(timeout.bind(null, --iterations), 1000);
}
}
The bind function simply binds the arguments of the bind function to the arguments of the timeout call - the first argument to the bind function declares its this scope; but don't worry about that too much.
You can modify the duration of the timer by changing the seconds var. Hope this helps :)
How do I stop JavaScript after execution?
I create one javascript for post in chat one text if other people say a keyword.
But the script send the message and not stop.
Now the code:
setInterval(function() {
jQuery('#frame_chatbox')
.replaceWith('<iframe id="framejqs" src="/chatbox" scrolling="yes" width="100%" height="100%" frameborder="0"></iframe>');
jQuery('#framejqs').contents()
.find('#chatbox_footer #chatbox_messenger_form #submit_button')
.click(function() {
if(jQuery('#framejqs').contents()
.find('#chatbox_footer #chatbox_messenger_form input[name="message"]')
.val().indexOf('HERE THE KEYWORD') != -1) {
$.post('/chatbox/chatbox_actions.forum?archives',
{mode:"send", sent:"HERE THE MENS"});
return false;
}
});
});
http://pastebin.com/5KF9R5Rv
It sends the message repeatedly because the sending function is wrapped in an interval firing once per millisecond (the second argument is missing):
setInterval(function () {
// ...
}, time_between_sends);
The time_between_sends defines how much time passes by between different calls of the function you passed into setInterval as first argument.
For example:
setInterval(function () {
console.log(new Date()); // logs the date once per second (1000ms === 1s)
}, 1000);
More generally, I'd consider using an event listener instead of an interval though.
You can simply use clearInterval
var interval = setInterval(function() {
//your code
if(condition to stop interval)
{
clearInterval(interval);//clearing interval when you want
}
});
Here is Live Demo
Update
If you want to stop it after you got response from post method you can do something like following:
DEMO
Code:
var myVar = setInterval(function(){
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
$.post('/echo/html/','',function(){
myStopFunction()//calling method to stop setInterval
});
}, 1000);
function myStopFunction() {
alert("stoping");
clearInterval(myVar);
}
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.