Ajax call back function scope & chaining Ajax request with callback - javascript

Ok. here's the scenario:
function DataFeed(){
function PopulateData()
{
$('div#example').load('http://www.example.com', fxnCallBack);
};
function fxnCallBack()
{
PopulateData();
}
this.activator = function() {
PopulateData();
}
};
var example_obj = new DataFeed;
example_obj.activator();
In the above code, the ajax .load gets executed once, then callback executes. But the callback doesn't start the ajax function again?
Thanks in advance.
edit- why doesn't it display new line properly -.-

InternalError: too much recursion
JavaScript engines normally have a max limit in the number of recursions or the time recursive execution may take. Use setInterval instead:
function DataFeed() {
var interval;
function PopulateData() {
$('div#example').load('http://www.example.com', function(data) {
if(data == "clear_interval")
interval = clearInterval(interval); // clear the interval
});
}
this.activator = function() {
interval = setInterval(PopulateData, 1000); // run every second
};
}
var example_obj = new DataFeed();
example_obj.activator();

Related

Call a function max once in a sec

I have a function that is used to send messages and that is called multiple times in a sec.
But I want to call that function once a sec and delay other calls of that function with another 1-second of the previous call.
So that only that function run in the background and called once in a second, no matters how many times it is called it will delay each call to one second ahead.
For example:
function foo(a) {
console.log(a)
}
foo('one');
foo('two');
foo('three');
in the above example, foo is called three times within a sec but I want to have it called like after the 1 second it should return "one" after 2 seconds it should return 'second' and so on and it should be asynchronous.
How can I do this?
The technology I am using is Javascript.
Thanks
Well this is the first thing I came up with - perhaps it's crude.
var queuedUpCalls = [];
var currentlyProcessingCall = false;
function foo(a) {
if (currentlyProcessingCall) {
queuedUpCalls.push(a);
return;
}
currentlyProcessingCall = true;
setTimeout(function(){
console.log(a);
currentlyProcessingCall = false;
if (queuedUpCalls.length) {
var nextCallArg = queuedUpCalls.shift();
foo(nextCallArg);
}
},1000);
}
foo('one');
foo('two');
foo('three');
For each call, if you're not currently processing a call, just call setTimeout with a delay of 1000ms. If you are processing a call, save off the argument, and when the setTimeout that you kicked off finishes, process it.
Somewhat improved answer using setInterval:
var queuedUpCalls = [];
var timerId;
function foo(a) {
queuedUpCalls.push(a);
if (timerId) {
return;
}
timerId = setInterval(function(){
if (!queuedUpCalls.length) {
clearInterval(timerId);
timerId = null;
return;
}
var nextCallArg = queuedUpCalls.shift();
console.log(nextCallArg);
}, 1000);
}
foo('one');
foo('two');
foo('three');
Here is a simple queue system, it basically just pushes the functions onto an array, and then splice's them off every second.
const queue = [];
setInterval(function () {
if (!queue.length) return;
const f = queue[0];
queue.splice(0, 1);
f();
}, 1000);
function foo(a) {
queue.push(function () {
console.log(a)
});
}
foo('one');
foo('two');
foo('three');
you could use this to run the main code first and then run some more code a little later.
function firstfunction() {
alert('I am ran first');
setTimeout(function(){ alert('I am ran 3 seconds later') }, 3000);
}
<button onclick="firstfunction();">click me</button>
function foo(a)
{
if (typeof foo.last == 'undefined')
foo.last = Date.now();
var now = Date.now();
if (now - 1000 > foo.time)
foo.last = now;
setTimeout(function()
{
console.log(a);
}, (foo.last += 1000) - now);
}
This will queue each console.log call with intervals of 1 second, the first call will also be delayed by 1 second.
You could do this:
function foo() {
console.log(“ran”);
}
setInterval(foo, 1000);
In the last line, writing foo() without parenthesis is intentional. The line doesn’t work if you add parentheses.

setInterval fires Ajax call twice every time

I have the following JS code:
var delay = 5000;
function init() {
setInterval(getFileCount, delay);
}
function getFileCount() {
$.get('/notification/course-file-count', function(response) {
if (response.items.length === 0) {
return false;
}
// Do stuff with response
});
}
On page load I'm calling the init() function. The idea is to start the interval and call the getFileCount() function every 5 seconds.
So, the interval waits 5s after the page loads and runs, but it always makes the Ajax call twice.
What am I missing?
UPDATE:
I know the init() function is triggered twice on page load (thanks to the comment by Yury Tarabanko). I don't quite understand, why. The almost-full code:
$(function() {
'use strict';
function handleCourseNotification() {
var delay = 5000;
function init() {
setInterval(getFileCount, delay);
}
function getFileCount() {
$.get('/notification/course-file-count', function(response) {
if (response.items.length === 0) {
return false;
}
updateCourseList(response.items);
});
}
function updateCourseList(items) {
// update course list...
}
return {
init: init
};
}
if ($('#js-auth-course-list').length) {
var notificationHandler = handleCourseNotification();
notificationHandler.init();
}
});
It's a small module, which I initialize after page load, if a specific element is available in the DOM - $('#js-auth-course-list'). Why is init called 2 times actually? I directly call it once.
In general, it is not a good idea to call asynchronous calls inside a setInterval() because you do not know the exact response time. So, you could end up calling the second async function before the response from the first call has returned.
You can try with setTimeout() like this:
var delay = 5000;
var async = function() {
$.get('/notification/course-file-count', function(response) {
if (response.items.length === 0) {
return false;
}
// Do stuff with response
// Call the async function again
setTimeout(function() {
async();
}, delay);
});
}
async();

How to stop a self-called setTimeout() function?

I have a count down function. The function used setTimeout() to repeatedly call itself:
function countDownSendCode(timer) {
if(timer >= 0) {
document.querySelector('#send-code').setAttribute('disabled', true);
document.querySelector('#send-code').innerHTML = timer + 's later resend';
setTimeout(function() {
countDownSendCode(timer - 1);
}, 1000);
} else {
document.querySelector('#send-code').removeAttribute('disabled');
document.querySelector('#send-code').innerHTML = 'Send';
}
}
The document.querySelector('#send-code') is a button used to send code. When a user click the button, he cannot click it again until the count down over.
I added below function to the button's click event to call the count down:
function clickSendCode(ev) {
ev.preventDefault();
countDownSendCode(5); // call the count down here
handleAjaxRequest();
}
In some case, in the handleAjaxRequest(), I need to stop the count down and make the button available immediately.
I can call countDownSendCode(-1) to set the button available, but how can I clear the setTimeout()? Because it called by it self, I cannot get the timeID required by clearTimeout().
You can achieve this functionality as shown in the following code snippet:
// global var serving as a handle to Timer
var _timer;
// call this function to start timer
function StartMyTimer()
{
_timer = setTimeout(function(){ alert("Hello, Timer is Running!"); }, 5000);
}
// call this function to stop timer
function StopMyTimer()
{
clearTimeout(_timer);
}
I would also suggest you to consider a pair of functions: setInterval() and clearInterval() which may simplify the coding of repetitive tasks.
Hope this will help.
I'd suggest not recursively calling countDownSendCode(). Rather just set the timer to the correct number of seconds to begin with, then you can return a ref to the timer and pass it to the ajax handler.
function countDownSendCode(timer) {
if(timer >= 0) {
document.querySelector('#send-code').setAttribute('disabled', true);
document.querySelector('#send-code').innerHTML = timer + 's later resend';
countDownSendCode._timer = setTimeout(function() {
countDownSendCode(timer - 1);
}, 1000);
}
else {
if('stop'===timer){
clearTimeout(countDownSendCode._timer);
}
document.querySelector('#send-code').removeAttribute('disabled');
document.querySelector('#send-code').innerHTML = 'Send';
}
}
modify the countDownSendCode function as above. call it with 'stop' string when you need the button to be available immediately.

Run a function repeatedly 10 seconds after it has completed (JavaScript)

I have a function that uses "post" to get data from the server and process it. Amount of data varies and the function can take a long time to complete (30 seconds). I would like for the function to be called repeatedly but only 10 seconds after it has completed the previous iteration. *Result of the function is stored in a global and is used in the next iteration of the same function.
I've tried setInterval and setTimeout but neither one of those seem to give me the result I'm looking for.
Any thoughts?
function foo(){
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
// do your stuff with returned data
// and call itself again...
setTimeout(foo, 10000);
});
}
Wouldn't this approach work?
function a(){
//do stuff
setTimeout(a, 10000); //has to be at the end of the execution. If you're doing things asynchronously that's a different story.
}
function setTimeout() can be used for this. But the method must be invoked for the first time then the function itself invoke the method again.
function method(){
console.log('method invoked');
setTimeout(method, 10000);
}
method();
var $id = 1;
var Interval ;
$(function(){
callAjax();//Starts Interval
});
functoin callAjax()
{
Interval = setInterval(function () {
try {
if($id > 0)
{
$.ajax({
url: _MyUrl + $id,
success: function (calbkData) {
$id = 0;
if (parseInt(calbkData.id) > 0) {
$id = calbkData.id;
OpenMsg(calbkData.id);
}
},
global: false, // this makes sure ajaxStart is not triggered
dataType: 'json'
//,complete: longpoll
});
}
} catch (e) {
// alert(e);
}
}, 10000);
}
This is working very fine, for me.
function Test()
{
//Your code here
setTimeout(Test(),10000);
//Its used to set time interval after your iteration is run
}

Prevent JS code to run, before function has ended

I can't wrap my head around this one?
WHY IS IT THAT MY:
.each loop runs right through even though I'm stalling things inside by 1000ms per loop?
The problem is that the window.location.href command runs TO EARLY before the setTimeout has finished? Same for the stopload() function which is also ended to early? I have seen something about recursive setTimeout functions is that what is needed here and how do I implement that?
function shop(clickedButton)
{
var buttonvalue = $(clickedButton).val();
startLoad();
pdel = 1000;
$("input:submit[value='buy']").each(function(index)
{
if(index != 1)
{
$("#backgroundPopup").text(index);
var submithing = this;
setTimeout(function(){ clicksubmitbutton(submithing); },pdel);
pdel += 1000;
}
});
stopLoad();
if(buttonvalue == "1")
{
window.scrollTo(0,0);
}
else
{
window.location.href = 'http://my.url';
}
}
Javascript has no notion of a sleep, or stall. Execution continues right past a setTimeout call. This function simply schedules a function to be run after the given number of milliseconds.
In order to get your desired behavior, you need to call the next iteration in the setTimeout callback function.
Something like:
function submitTheThing(index) {
if (done) { //some logic
return;
}
// do something
setTimeout(function() { submitTheThing(index+1); }, 1000);
}

Categories