I'm new at jQuery and I really hope I can get help with this problem as it is causing me significant headache.
Here is my code:
$(function() {
var global = '0'
run(); // run function run on page load.
function run(){
var cars = new Array("Saab", "Volvo", "BMW");
var wait = new Array("2000", "5000", "10000");
alert (cars[global]);
WAIT (wait[global]) THEN run function cars AGAIN {
run();
global++;
if (global == 4) {
global = '0';
}
}
}
});
So as you can see: on page load function run() runs, alerting "Saab". THEN the function should wait 2000ms and re-run iself. On the next run function run would alert "Volvo" and wait 5000ms before re-running itself. On the third run it would alert "BWM" and wait 10000ms then resetting the global variable to 0 and doing it all over again.
So basically what I will do is populate the two arrays with different variables and create alerts based on user-defined delays.
Thank you so much in advance!
You mean SetTimeout that is used to run code after x amount of milliseconds (here more).
Here is a working solution:
$(function() {
var global = '0'
run(); // run function run on page load.
function run(){
var cars = new Array("Saab", "Volvo", "BMW");
var wait = new Array("2000", "5000", "10000");
alert (cars[global]);
setTimeout(function(){
global++;
if (global == 3){
global = '0';
}
run();
}, wait[global]);
}
})
Here is JSFiddle to it.
I moved:
global++;
if (global == 3){
global = '0';
}
Before the function call as if the call is before increment, it would call the function with global = 0 again first. If you are unsure what I mean by that, try with JSFiddle.
Just clean a bit the code (for fun), here is my code (same code blocks just rearranged):
$(function() {
var cars = new Array("Saab", "Volvo", "BMW");
var wait = new Array("2000", "5000", "10000");
var global = '0'
run(); // Initial run.
function run(){
if (global == 3){
global = '0';
}
alert (cars[global]);
global++;
setTimeout(function(){
run();
}, wait[global]);
}
})
<script>
var index = 0;
var cars = [];
$( document ).ready(function() {
var obj = {car: "Volvo", timeout: "2000"};
cars.push(obj);
var obj = {car: "Saab", timeout: "5000"};
cars.push(obj);
var obj = {car: "BMW", timeout: "10000"};
cars.push(obj);
alertAndReRun();
});
function alertAndReRun(){
console.log(index + " " + (cars.length-1));
alert(cars[index].car);
index++;
if(index <= (cars.length-1)){
setTimeout(alertAndReRun, cars[index].timeout);
}
}
</script>
You can set a timeout before running the function again with window.setTimeout.
Here is a recursive solution for your problem:
$(function() {
var cars = ["Saab", "Volvo", "BMW"];
var wait = ["2000", "5000", "10000"];
var index = 0;
run();
function run() {
if(cars.length < index + 1 || wait.length < index + 1) {
index = 0;
}
var car = cars[index];
var waitingTime = wait[index];
// do something with `car`
console.log(car);
index++;
window.setTimeout(run, waitingTime);
}
});
This example works as you expected, using setInterval()
$(function() {
var timer = null;
run();
function run(){
var cars = new Array("Saab", "Volvo", "BMW");
console.log(cars[global]);
global++;
if (global == 3) {
global = 0;
}
if (timer !== null) {
clearInterval(timer);
}
timer = setInterval(run, parseInt(wait[global]));
}
});
And here a JSFiddle: Time Variable interval
Related
I am having some problem using the settimeout() in my function. I am new to async. No matter how much I try I just can't make the timeout work. My code works perfect so that is not the problem. I need the request to execute every 10 seconds. Thanks for the help.
function getContent() {
function getPelicula(pelicula, donePelicula) {
var peli = pelicula.title;
//request id
request({
url: "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false",
method: "GET",
json: true,
}, function(error, res, body) {
if (error) {
console.error('Error getPelicula: ', error);
return;
}
var control = body.results.length;
if (control > 0) {
var year_base = pelicula.launch_year;
var id = body.results[0].id;
var year = body.results[0].release_date;
var d = new Date(year);
var year_solo = d.getFullYear();
if (year_base == year_solo) {
pelicula.id = id;
pelicula.year_pagina = year_solo;
}
} else {
pelicula.id = null;
pelicula.year_pagina = null;
}
donePelicula();
});
}
}
To do something in a loop, use setInterval.
UPD:
In general, there're two ways of executing some code in loop
1 setTimeout :
var someTimer = setTimeout(function sayHello(){
console.log("hello!");
someTimer = setTimeout(sayHello, 2000);
}, 2000);
Notice that someTimer variable is needed to stop the looping process if you need: clearTimeout(someTimer)
2 setInterval:
var someIntervalTimer = setInterval(function(){
console.log("I'm triggered by setInterval function!");
}, 2000);
Invoke clearInterval(someIntervalTimer) to stop the looping
Both functions are treated as properties of the global Window variable. By default, the following code works:
var window = this;
console.log("type of setTimeout: " + typeof window.setTimeout);
console.log("type of setInterval: " + typeof window.setInterval);
Try putting it in another function so:
domore(pelicula,donePelicula);
function domore(pelicula,donePelicula) {
// 1 second
var timeout = 1000;
for (var i = 1; i < pelicula.length; i++) {
createData(pelicula[i],donePelicula,timeout);
timeout = timeout + 800;
}
}
function createData(peli,donePelicula,timeout) {
setTimeout(function() { getData(peli,donePelicula); }, timeout);
}
function getData(peli,donePelicula) {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
domore(allText,donePelicula);
}
}
}
txtFile.send(null);
}
I'm willing to create a function that changes payhighx() into paylowx() and paylowx() into payhighx() each time one of the two is executed. I thought of an if statement going into the roll() function that'd check whether payhighx()/paylowx() was executed and change their properties if the returned value is True. I tried researching something related to my problem, but couldn't find anything useful in terms of JQuery and Javascript.
var start = 0.01
var $input = $("#oddsInput")
var $odds = $("#oddsOverUnder")
var $button = $("#roll")
var $bet = $("#bet")
var $pay = $("#oddsPayout.btn.btn-primary.btn-xlg.btn-block")
function paylowx() {
$pay.click()
document.getElementById("oddsInput").value = "1.2";
$odds.click()
}
function payhighx() {
$pay.click()
document.getElementById("oddsInput").value = "5.2";
$odds.click()
}
function roll() {
$bet.val(start)
$button.click()
setTimeout(function() {
var tr = document.querySelector("#myBetsTable tr:nth-child(2)")
var cls = tr.getAttribute('class')
if (cls === 'success'){
}
else{
payhighx()
}
$button.click();
setTimeout(function()
{
$button.click();
},1000);
},1000);
}
setInterval(roll, 2000)
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.
I am using a simple countdown as such below which is working fine except when it is placed in the loop. During looping both previous and new counter remains working .I want to kill the previous counter and start with a new, which i am not able to achieve. Can anybody help on this please
function triggerEvery60Sec(){
var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
}
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
Instead of declare your variable in the loop, maybe should you declare it before, and manipulate it during your loop.
var myCounter = null;
function triggerEvery60Sec(){
myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
}
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);
}