in this code i want to when div with .ch1 class changed background to answer_box_small_orange.png other bottom js lines code don't run and no ajax request sends until 3 seconds and i used
window.setTimeout(function () {}, 3000)
but it doesnt work correctly
here first of all i request and get data and it is ok
$.ajax({
type:'post',
url:'http://207.154.251.233:8039/app.php/question/get',
data:JSON.stringify({apikey:'jwebdpqodp9fgkwjebfkdpqihdqlwkndqp'}),
success:(function (response) {
var x = response;
$("#question").text(x.result.question);
$(".op1").text(x.result.options["1"]);
})
});
i inserted ajax code and some other codes in function because i want to run it every 60 seconds
function myInterval () {
$(".ch1").css('background-image','url(image/answer_box_small.png)');
var clock;
$(document).ready(function() {
clock = new FlipClock($('.clock'), 60, {
clockFace: 'Counter',
autoStart: true,
countdown: true,
callbacks: {
stop: function() {
$('#loading').fadeIn('5000');
$.ajax({
type:'post',
url:'http://79.175.166.98/',
data:JSON.stringify({apikey:'jwebdpqodp9fgkwjebfkdpqihdqlwkndqp'}),
success:(function (response) {
$('#loading').fadeOut('slow');
var x = response;
$("#question").text(x.result.question);
$(".op1").text(x.result.options["1"]);
var answer = x.result.answer;
if(answer == 1){
$(".ch1").css('background-image','url(image/answer_box_small_orange.png)');
}
window.setTimeout(function () {}, 3000);
})
});
}
}
});
});
}
myInterval();
window.setInterval(function(){
myInterval();
}, 60000);
Based on what you told me, my interpretation is that you have a setTimeout() function and a setInterval() function. The setTimeout() runs at the beginning and will wait for 3 seconds. Then call an ajax function to create new requests every 6 seconds. Your problem seems to be that your first setTimeout() is re-run after you create your first AJAX request, but you want it to stop.
Taken from W3
setTimeout Return Value: A Number, representing the ID value of the timer that is set. Use this value with the clearTimeout() method to cancel the timer.
Knowing this, we can essentially cancel a setTimout() function. In your case, the first setTimeout().
Consider this,
var firstIntervalID = setTimeout(function() {
$.ajax() {
// First AJAX ran after three seconds.
}
}, 3000);
clearTimeout(firstIntervalID);
// Your code resumes to set an interval every 60 seconds without having to worry about the three seconds set before
myInterval();
var secondIntervalID = setInterval(function(){
myInterval();
}, 60000);
Essentially, you cancel the setTimeout() when you don't need it anymore. Your application for it can be different than what I wrote, but the main idea is the same. Cancel/Clear the setTimeout() with the ID that is returned on setTimeout() with clearTimeout().
Related
I have the code below.
var intervalId;
function myCallback() {
$.ajax({
url: "http://bla.html",
cache: false,
success: function(data) {
if (intervalId) {
clearInterval(intervalId);
}
if (data && data.result) {
return;
}
alert(data.result);
}
, timout: 2000
});
}
function callInterval() {
intervalId = setInterval(myCallback, 5000);
}
callInterval();
The problem is that the "clearInterval(intervalId)" doesn't seems to invalidate the interval at this right time because the message alert is shown twice.
So here is my question, is clearInterval(intervalId) asynchronous?
The point is not about being the clearInterval sync or async.
In your code you start the interval the first time, and then after every second you execute your myCallback.
Clearing the interval when you get back a response, means that during the time that the ajax request is performing, the interval is still running and will start new ajax requests.
How do I make my list update in real time with jquery but without loads of request?
function startInterval() {
checkInt = setInterval(function() {
$("#queueOrderList").load("updateQueueList.php function() {
console.log("Load was performed");
});
}, 100)
}
This is my code and it makes 10 requests per second.
My objective is to keep a user in a view as long as he/she keeps clicking a button within a certain lapse.
I'm using Rails and was exploring a solution via an embedded JS in the pertinent view.
So far I'm able to set a time after which the user will be redirected to root path with the following script:
var delayedRedirect = function (){
window.location = "/";
}
var delay = 10000;
$(document).ready(function() {
setTimeout('delayedRedirect()', delay);
});
I've been trying to write a function that resets the value of 'delay'or that calls the setTimeoutFunction again.
$('#btn-persist').click(function() {
delay = 3000;
// or calling again setTimeout('delayedRedirect()', delay);
});
But I noticed that changing the variable won't affect the setTimeout function that has already been called.
I've also tried to use the clearTimeout function as below without success
var delayedRedirect = function (){
window.location = "/persists";
}
var delay = 3000;
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
var stopRedirect = function (){
clearTimeout(triggerRedirect);
}
$(document).ready(function() {
triggerRedirect();
$('#btn-persist').click(function() {
stopRedirect();
});
});
I wonder why this may not be working and if there's any other way to stop the execution of the setTimeout function that has already been called so I can call it again to effectively reset the time to the original value of 'delay'.
At the same time, I don't want to stop any other JS functions that are running in parallel.
Do you see a better solution to achieve this?
The main problem why clearTimeout is not working. because you are clearing a anonymous function instead of a setTimeout variable
change this
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
to this
var triggerRedirect = setTimeout('delayedRedirect()', delay);
Edit:
also change this (if you want to restart the inactive redirect trigger)
$('#btn-persist').click(function() {
stopRedirect();
});
to this
$('#btn-persist').click(function() {
stopRedirect();
triggerRedirect();
});
<script>
Main Function:
var interval;
function refreshId(session_to_user) {
interval = setInterval(function()
{
$('.chat-box').load("<?php echo base_url()."users/message/refresh_div/"; ?>" + session_to_user);
}, 10000);
}
in this main function I'm only going to perform my requirement here. I have a variable interval my enabling this function, and it will refresh every 10 seconds.
onclick of function
forloop
{
<a href = "" onclick="myFunction(user_id)"
}
function myFunction(user_id){
clearInterval(interval);
$.ajax({
success:function(data)
{
$('.chats').html(data);
}
})
refreshId(session_to_user);
}
If anyone clicks on href, it should clearInterval if already exists else a new Interval has to be established on click function. In my current code, it works if I click for the first time. It starts refreshing the first link for every 10 seconds, but when I click for the second time on the second link, it waits. Still, the first one gets executed and then the second one is executing. My requirement is if I click, the established setInterval has to stopped instantly and the new one has to be started on the spot same as for my next function paper_plane() also.
function paper_plane()
{
clearInterval(interval);
$.ajax({
success:function(html)
{
$('#chat').append(html);
$('.chat-input').val('');
$('.chat-input').focus();
}
});
}
var side_bar_path = "<?php echo base_url()."users/message/load_side_bar"; ?>";
$.ajax({
success : function(data)
{
$('.msg-list').html(data);
}
});
refreshId(session_to_user);
}
There is no way you can cancel the ajax request after the delay(10 seconds) is elapsed from first click handler,since it would not return the result immediately.
so the only way you can cancel the previous ajax calls before making a new ajax call is to suppress/ignore the responses of the previous ajax calls once the second link is triggered, this way you will create a scenario what your expecting.
Below i have created a small snippet which will do the scenario mentioned above.
JS Code:
var firstTimer;
//first click handler
$('#first').on('click',function () {
firstTimer= setInterval(function (){
$.ajax({
url:"http://target.org/page.html",
dataType: "POST",
data:{'name1':'davy'}
success: function(data) {
//suppress the response when timer is stopped.
if(firstTimer>0){
return;
}
//if timer is not stopped process the data
},
error :function(error) {
//handle error
}
});
},1000);
});
//second click handler
$('#second').on('click',function () {
//clear the firstTimer before staring a new timer
clearInterval(firstTimer);
var timer;
timer = setInterval(function (){
$.ajax({
url:"http://target.org/page2.html",
dataType: "POST",
data:{'name1':'rog'}
success: function(data) {
//process the data
},
error :function(error) {
//handle error
}
});
},1000);
});
I'm not sure if this is possible or not but.
If I have a php file I'm calling like so
<?php include 'number.php';?>
which is a number that will increase every hour or two.
How can I actively check if the number has changed?
When the number increases how can I trigger a sound alert followed by a redirect?
What I'm currently doing is using a "refresh every 5 seconds" within number.php
<body onload="setInterval(function() {window.location.reload();}, 5000);">
Then I'm trying to use jquery to console log the number and check for increased values, but I realized that it wasn't going to happen so I will spare you the messy code.
This is what I'm trying to trigger:
$("#alert").get(0).play();
$(location).attr('href', 'http://stackoverflow.com')
Any solution is fine. Also I'm starting to think an iframe is the way to go.
Use an Ajax request:
$(document).ready(function () {
// Declare the var
var num = 0;
// Function to be called every 5 secs
var update = function() {
$.ajax({
url: '/number.php',
type: 'get',
success: function (output) {
return output;
}
});
};
// Every 5 secs call update(), check if return a number > 0, and add it to num var
setInterval(function () {
var out = update();
if (out > 0) {
num += out;
}
console.log(num);
}, 5000);
});