javascript settimeout not working inside recursive function - javascript

My script is as follows which should replay mouse image inside a div but settimeout is not working and there is no error in console also:
function play(data, value) {
var data = data;
function run() {
var nowTime;
var newdata = data.splice(0, 1); // after splice, data will be auto updated
if (newdata.length == 1) {
nowTime = newdata[0][6];
var timer = setTimeout(function() {
if (newdata[0][3] == '14') {
replay(newdata[0][0], newdata[0][1]);
}
preTime = nowTime;
// continue run next replay
run();
}, nowTime - preTime);
}
}
run();
}
Please help me. How to solve this issue.
thanks in advance

try this
var newdata;
var nowTime;
var preTime;
function play(data, value)
{
newdata= data.splice( 0, 1 ); // after splice, data will be auto updated
if ( newdata.length == 1 ) {
nowTime = newdata[0][6];
var timer = setTimeout("timer();",nowTime - preTime );
}
}
function timer()
{
if(newdata[0][3] == '14'){
replay( newdata[0][0], newdata[0][1]);
}
preTime = nowTime;
play();
}
play();

Related

How to delay a JavaScript JSON stream for one minute?

I am ask to write a java script program that retrieve an api JSON record from and address and through websocket every single minute. The stream continues after 60 seconds. I am expected to return the respective stream retrieve and the stream from the previous retrieve . Below is my code
var obj=
{
seconds : 60,
priv : 0,
prevTick : '' ,
data : ''
}
function countTime()
{
obj.seconds --;
obj.priv ++;
var msg ;
if(obj.priv > 1)
{
obj.priv = 0;
obj.msg = null;
}
if(prop.seconds < 0)
{
msg = sock.open();
obj.msg = obj.msg + ", New Tick : " + msg.msg ;
setTimeout(countTime, 1000);
obj.seconds = 60;
}
}
var sock= new WebSocket('link');
sock.onopen = function(evt) {
ws.send(JSON.stringify({ticks:'string'}));
};
sock.onmessage = function(msg) {
var data = JSON.parse(msg.data);
return 'record update: %o'+ data ;
};
Please what is wrong with my code above ? It does not delay at all. The stream continues irrespective.
How about encapsulating the buffering behavior into a class?
function SocketBuffer(socket, delay, ontick) {
var messages = [], tickInterval;
socket.onmessage = function(msg) {
messages.push( JSON.parse(msg.data) );
};
function tick() {
if (typeof ontick !== "function") return;
ontick( messages.splice(0) );
}
this.pause = function () {
tickInterval = clearInterval(tickInterval);
};
this.run = function () {
if (tickInterval) return;
tickInterval = setInterval(tick, delay * 1000);
tick();
};
this.run();
}
Note that .splice(0) returns all elements from the array and empties the array in the same step.
Usage:
var link = new WebSocket('link');
link.onopen = function (evt) {
this.send( JSON.stringify({ticks:'string'}) );
};
var linkBuf = new SocketBuffer(link, 60, function (newMessages) {
console.log(newMessages);
});
// if needed, you can:
linkBuf.pause();
linkBuf.run();
Try this:
function countTime() {
var interval = 1000; // How long do you have to wait for next round
// setInterval will create infinite loop if it is not asked to terminate with clearInterval
var looper = setInterval(function () {
// Your code here
// Terminate the loop if required
clearInterval(looper);
}, interval);
}
If you use setTimeout() you don't need to count the seconds manually. Furthermore, if you need to perform the task periodically, you'd better use setInterval() as #RyanB said. setTimeout() is useful for tasks that need to be performed only once. You're also using prop.seconds but prop doesn't seem to be defined. Finally, you need to call countTime() somewhere or it will never be executed.
This might work better:
var obj=
{
seconds : 60,
priv : 0,
prevTick : '' ,
data : ''
}
function countTime()
{
obj.seconds --;
obj.priv ++; //I don't understand this, it will always be set to zero 3 lines below
var msg ;
if(obj.priv > 1)
{
obj.priv = 0;
obj.msg = null;
}
msg = sock.open();
obj.msg = obj.msg + ", New Tick : " + msg.msg;
obj.seconds = 60;
//Maybe you should do sock.close() here
}
var sock= new WebSocket('link');
sock.onopen = function(evt) {
ws.send(JSON.stringify({ticks:'string'}));
};
sock.onmessage = function(msg) {
var data = JSON.parse(msg.data);
return 'record update: %o'+ data ;
};
var interval = setInterval(countTime, 1000);
EDIT: finally, when you're done, just do
clearInterval(interval);
to stop the execution.

Stopping a function from running

I have 3 sequential divs to display on a page, the page loads showing div 1, by going onto the 2nd it starts a timer, when that timer runs out it goes back to the first div. Navigating through to the next div should start the timer again. The timer function works OK on the first page but on the second page when it is called it is already running from the previous div and therefore ticks the time down twice as fast, and on the last div 3 times.
How can I get it to stop the currently running function then restart it?
Thanks,
$scope.timeLeft = 0;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
run();
}
timeoutRunner(5);
You need to add some logic that calls $timeout.cancel(timeoutRunner);.
Not sure where you want to cancel your timeout exactly (view change? when you end the transaction?) But here is how you would do it:
$scope.timeLeft = 0;
var timeoutPromise = false;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
timeoutPromise = $timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
$timeout.cancel(timeoutPromise);
}
}
run();
}
timeoutRunner(5);
Each time I called the function it created a new instance of it and I was unable to stop it on demand so I found a way to say which instance I want running:
$scope.timeLeft = 0;
var instanceRunning = 0;
var timeoutRunner = function (timerLength, instance) {
$scope.timeLeft = timerLength;
instanceRunning = instance;
var run = function () {
if (instanceRunning == instance){
if ($scope.timeLeft < 7 && $scope.timeLeft > 0){
$('#timer-container').show();
} else {
$('#timer-container').hide();
}
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
}
run();
}
timeoutRunner(20, 1);
timeoutRunner(20, 2);
timeoutRunner(20, 3);

Infinite Loop in Page Redirection Function of JavaScript

I am now working on a piece of code of JavaScript which will be used to redirect a page with a shown counter. The problem is, when counter reaches 0, countDown() function gets in an infinite loop which causes the page to remain the same. And of course, I could not resolve the problem yet. Can anyone help?
You can see the problem here:
http://kibristaodtuvarmis.com/index.html
Code is shown below:
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function countDown()
{
if (time == 0)
{
window.location = page;
return(0);
}
else
{
time--;
gett("container").innerHTML = time;
}
}
function gett(id)
{
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init()
{
if(gett("container"))
{
setInterval(countDown, 1000);
gett("container").innerHTML = time;
}
else
{
setTimeout(init, 50);
}
}
document.onload = init();
EDIT:
I have done the below changes in countDown() function and problem is resolved:
var control = false;
function countDown()
{
if (time == 0 && control == false)
{
control = true;
window.location = page;
return(0);
}
else if (time > 0)
{
time--;
gett("container").innerHTML = time;
}
else
{
return(0);
}
}
I would do something like this:
var b = false;
if (time == 0 && b == false)
{
b = true;
window.location = page;
return(0);
}
Try this part of code for by replacing your complete javascript Code :
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function startCount() {
time = time - 1;
console.log(time);
document.getElementById("container").innerHTML = time;
startCounter();
}
function startCounter() {
if (time !== 0) {
setTimeout(function () {
startCount();
},1000);
} else {
location.href = page;
}
}
if (window.addEventListener) {
window.addEventListener("load", startCount, false);
} else if (el.attachEvent) {
window.attachEvent("load", startCount);
}
I tried it, It works.
Tell me your reply after testing.
Are you wanting it to stop at 0? Assign the setInterval to a var and then use clearInterval if 0
your setIinterval continues executing before change the window.location and then causes this loop because time is 0 and should launch window.location again
you should clear the interval
var IdInterval = setInterval(function () {
//.... code
}, 10000);
and after the first execution of countDown with time==0 then:
clearInterval(IdInterval);

countdown timer stops at zero i want it to reset

I am trying to figure out a way to make my countdown timer restart at 25 all over again when it reaches 0. I dont know what I am getting wrong but it wont work.
Javascript
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
fn();
//stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
//set it going
countDownObj.count(i);
}
function myFunction(){};
</script>
HTML
<div id="countDown"></div>
try this, timer restarts after 0
http://jsfiddle.net/GdkAH/1/
Full code:
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
startCountDown(25, 1000, myFunction);
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
}, pause);
}
// set it going
countDownObj.count(i);
}
function myFunction(){};
​
I don't see you resetting the counter. When your counter goes down to 0, it executes the function and return. Instead, you want to execute the function -> reset the counter -> return
You can do this by simply adding i = 25 under fn() :
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
i = 25;
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
// set it going
in #Muthu Kumaran code is not showing zero after countdown 1 . you can update to this:
if (i < 0) {
// execute function
fn();
startCountDown(10, 1000, myFunction);
// stop
return;
}
The main reason for using setInterval for a timer that runs continuously is to adjust the interval so that it updates as closely as possible to increments of the system clock, usually 1 second but maybe longer. In this case, that doesn't seem to be necessary, so just use setInterval.
Below is a function that doesn't add non–standard properties to the element, it could be called using a function expression from window.onload, so avoid global variables altogether (not that there is much point in that, but some like to minimise them).
var runTimer = (function() {
var element, count = 0;
return function(i, p, f) {
element = document.getElementById('countDown');
setInterval(function() {
element.innerHTML = i - (count % i);
if (count && !(count % i)) {
f();
}
count++;
}, p);
}
}());
function foo() {
console.log('foo');
}
window.onload = function() {
runTimer(25, 1000, foo);
}

Looping functions with timeout

I want to have two functions (an animation downwards and animation upwards) executing one after the other in a loop having a timeout of a few seconds between both animations. But I don't know how to say it in JS …
Here what I have so far:
Function 1
// Play the Peek animation - downwards
function peekTile() {
var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
// Reposition tiles to their desired post-animation position
tile1.style.top = "-150px";
tile2.style.top = "-150px";
peekAnimation.execute();
}
Function 2
// Play the Peek animation - upwards
function unpeekTile() {
var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
// Reposition tiles to their desired post-animation position
tile1.style.top = "0px";
tile2.style.top = "0px";
peekAnimation.execute();
}
And here's a sketch how both functions should be executed:
var page = WinJS.UI.Pages.define("/html/updateTile.html", {
ready: function (element, options) {
peekTile();
[timeOut]
unpeekTile();
[timeOut]
peekTile();
[timeOut]
unpeekTile();
[timeOut]
and so on …
}
});
You can do this using setTimeout or setInterval, so a simple function to do what you want is:
function cycleWithDelay() {
var delay = arguments[arguments.length - 1],
functions = Array.prototype.slice.call(arguments, 0, arguments.length - 1),
pos = 0;
return setInterval(function () {
functions[pos++]();
pos = pos % functions.length;
}, delay);
}
Usage would be like this for you:
var si = cycleWithDelay(peekTile, unpeekTile, 300);
and to stop it:
clearInterval(si);
This will just cycle through the functions calling the next one in the list every delay msec, repeating back at the beginning when the last one is called. This will result in your peekTile, wait, unpeekTile, wait, peekTile, etc.
If you prefer to start/stop at will, perhaps a more generic solution would suit you:
function Cycler(f) {
if (!(this instanceof Cycler)) {
// Force new
return new Cycler(arguments);
}
// Unbox args
if (f instanceof Function) {
this.fns = Array.prototype.slice.call(arguments);
} else if (f && f.length) {
this.fns = Array.prototype.slice.call(f);
} else {
throw new Error('Invalid arguments supplied to Cycler constructor.');
}
this.pos = 0;
}
Cycler.prototype.start = function (interval) {
var that = this;
interval = interval || 1000;
this.intervalId = setInterval(function () {
that.fns[that.pos++]();
that.pos %= that.fns.length;
}, interval);
}
Cycler.prototype.stop = function () {
if (null !== this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
Example usage:
var c = Cycler(peekTile, unpeekTile);
c.start();
// Future
c.stop();
You use setInterval() to call unpeekTile() every 1000 milliseconds and then you call setTimeOut() to run peekTile() after 1000 milliseconds at the end of the unpeekTile() function:
function peekTile() {
var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
// Reposition tiles to their desired post-animation position
tile1.style.top = "-150px";
tile2.style.top = "-150px";
peekAnimation.execute();
}
function unpeekTile() {
/* your code here */
setTimeout(peekTile, 1000);
}
setInterval(unpeekTile, 1000);
Check out the fiddle
var animation = (function () {
var peekInterval, unpeekInterval, delay;
return {
start: function (ip) {
delay = ip;
peekInterval = setTimeout(animation.peekTile, delay);
},
peekTile: function () {
//Your Code goes here
console.log('peek');
unpeekInterval = setTimeout(animation.unpeekTile, delay);
},
unpeekTile: function () {
//Your Code goes here
console.log('unpeek');
peekInterval = setTimeout(animation.peekTile, delay);
},
stop: function () {
clearTimeout(peekInterval);
clearTimeout(unpeekInterval);
}
}
})();
animation.start(1000);
// To stop
setTimeout(animation.stop, 3000);
​
I can't use this instead of animation.peekTile as setTimeout executes in global scope

Categories

Resources