javascript while loop - loops

<input type="button" onclick=openAPage()></>
i have a button
function openAPage() {
var startTime = new Date().getTime();
var myWin = window.open("http://www.sabah.com.tr","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;
myWin.close()
document.write("<br>button pressed#</br>")
document.write(new Date(startTime));
document.write("<br>page loaded#</br>")
document.write(new Date(endTime));
document.write("<br>time taken</br>")
document.write(timeTaken);
}
and have a function
i want to call this function every 5 minutes? is it possible?

setInterval( function(){
openAPage();
}, 5*60*1000);
and setTimeout does it once.

It's very easy with jQuery.
window.setInterval(openAPage, 60*5*1000);

var timer = setInterval( openAPage, 60*5*1000);

Related

How to check if 10 minutes is passed in angularjs?

So that is my question. Is it possible to do something like this:
DateTime.Now > Date.AddMinutes(10) ?? Problem is that its now add minutes on date ? How can i do that?
I need to check if 10 minutes is passed...
var start = new Date();
if(start.addMinutes(10) > Date.now())
{
$scope.isCancelTicketButtonVisible = true;
$scope.$emit("appIsCancelTicketButtonVisible", $scope.isCancelTicketButtonVisible);
}
You can use this approach-
var firstDate = new Date();
var finalDate = firstDate.setMinutes(firstDate.getMinutes() + 10);
Update
html
<div ng-bind="elapsed()"></div>
code
var startDate = Date.Now();
function elapsed(){
if(start.addMinutes(10) > Date.now()){
console.log('do stuff here');
}
}
Use the $timeout service like below. After a 'sleep period' of 10 minutes the code will execute.
$timeout(function() {
console.log('Timeout fired')
$scope.isCancelTicketButtonVisible = true;
$scope.$emit("appIsCancelTicketButtonVisible", $scope.isCancelTicketButtonVisible);
}, 600000);
Reference

function never ends - fileReader xlsx.js angularJS

I'm using the FileReader Object in combination with xlsx.js to import data from an Excel-Sheet into my AngularJS Web-App.
The function never gets ended, so I need to continue the script manually by invoking an empty dummy function check(){} manually by clicking on a button to continue my script. I don't know, why the script behaves like that.
Code of my controller:
$scope.fileChanged = function(files) {
var i,f;
f = files[0];
reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {type: 'binary'});
formData.data.teams = XLSX.utils.sheet_to_json(workbook.Sheets['latusch']);
var sheet_name_list = workbook.SheetNames;
var worksheet = workbook.Sheets['latusch'];
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
reader.readAsArrayBuffer(f);
}
readAsArrayBuffer is inside the onload callback, so it will not be called.
Remove it from the callback.

how can I clearInterval a timer in an another view ,in Backbone.js

this is my app jsfiddle
this App is a question test.
it has these function below:
choose a item,if correct,show some text and a next question link on a popup layer;
every question has a second countdown timer, if timeout, return some text;
if checked a item in time,the timer would stopped.
now I have trouble with the 3rd item, i don't know how to clearInterval the timer.
who can help me! thanks!
var TimerView = Backbone.View.extend({
el: $("#time-value"),
initialize: function () {
var self = this;
//console.log(this.model.get("seconds"));
//this.current = (new Date()).getSeconds();
var _t = new Date();
this.end = _t.setSeconds(_t.getSeconds() + Number(this.model.get("seconds")));
// this.end = (new Date(this.model.getTime() + this.model.seconds * 1000)).getTime();
this.model.on('change', this.render(), this);
},
cdInterval: '',
startCountdown: function () {
var self = this;
console.log('start countdown');
this.cdInterval = window.setInterval(function () {
self.render();
}, 10);
},
stopCountdown: function () {
console.log('stop countdown222');
clearInterval(this.cdInterval);
},
render: function () {
var end = this.end,
now = (new Date()).getTime(),
_second = 1000,
_minute = _second * 60,
diff = end - now;
if (diff <= 0) {
this.stopCountdown();
// app.navigate('qid/2', { trigger: true });
this.$el.html(" 00 : 000 ");
/*var result = new Result({
qid: '',
status: 3
});*/
app.result.set({
qid: app.id,
status: 3
});
/*(new PopupView({
model:app.result
})).render();*/
return false;
}
// some code....
}
});
jsfiddle

calling another method inside same view

I making a simple game that uses a two minute JavaScript timer. I can get the javascript timer to work without using backbone. The code is at the bottom for the working timer, and here's a fiddle of it http://jsfiddle.net/mjmitche/hDRjR/19/
However, once I try to the timer code into a few different methods inside a Backbone view, I'm getting an error depending on how a key method, displayTime, code is defined
Steps:
1) I create a new clockView and save it to a variable clock_view
var clock_view = new ClockView({ model: game});
Inside the initializer of clockview, I set up these variables that are used by the timer code
var totalWait = 120;
var secondsRemaining = totalWait;
var hasFocus = true;
var hasJustFailed = false;
The startClock method gets triggered from elsewhere
this.model.bind("gameStartedEvent", this.startClock, this);
startClock uses setInterval to call displayTime method every second. Depending on how displayTime is coded [a) displayTime(), b) this.displayTime(), c) clock_view.displayTime() ], displayTime triggers a different error.
startClock: function(){
console.log("start clock");
setInterval(function(){
this.secondsRemaining -= 1;
console.log("working");
displayTime(); //uncaught reference error: displayTime is not defined
this.displayTime(); //Uncaught TypeError: Object [object Window] has no method 'displayTime'
clock_view.displayTime();// `display time gets called but triggers NAN`
if(secondsRemaining == 0) $('#timer').fadeOut(1000);
}, 1000);
},
If displayTime is called from setInterval as displayTime() it says it's not defined. If I do this.displayTime(), I get a object window has no method. If I call it clock_view.displayTime(), it triggers a NAN error, which I think may be caused because the way the variables are defined in the initializer
displayTime is defined directly below startClock like this
displayTime: function () {
var minutes = Math.floor(secondsRemaining / 60);
var seconds = secondsRemaining - (minutes * 60);
if (seconds < 10) seconds = "0" + seconds;
var time = minutes + ":" + seconds;
$('#timer').html(time);
},
Update
This is a fiddle of the whole ClockView in a Backbone format, although it doesn't work because it's missing other parts of the program (such as the model that triggers the event). I'm including it only to make the question more readable
http://jsfiddle.net/mjmitche/RRXnK/85/
Original working clock code http://jsfiddle.net/mjmitche/hDRjR/19/
var displayTime = function () {
var minutes = Math.floor(secondsRemaining / 60);
var seconds = secondsRemaining - (minutes * 60);
if (seconds < 10) seconds = "0" + seconds;
var time = minutes + ":" + seconds;
$('#timer').html(time);
};
$('#timer').css('marginTop', 0);
setInterval(function(){
secondsRemaining -= 1;
displayTime();
if(secondsRemaining == 0) $('#timer').fadeOut(1000);
}, 1000);
This should work. The main points are, how variables are accessed inside the View.
HTML:
<div id="view">
<div id="timer">
<span class="time">2:00</span>
</div>
<div id="options">
<input type="button" class="action_button" value="New Game" id="new_game">
</div>
</div>
View:
var ClockView = Backbone.View.extend({
el: '#view',
initialize: function () {
/** Define your variables in this View */
this.totalWait = 120;
this.secondsRemaining = this.totalWait;
this.hasFocus = true;
this.hasJustFailed = false;
},
events: {
'click #new_game' : 'startClock' /** The button starts the clock */
},
startClock: function () {
console.log("start clock");
var self = this; /** Save 'this' to a local variable */
setInterval(function () {
self.secondsRemaining -= 1;
self.displayTime();
if (self.secondsRemaining == 0) self.$('#timer').fadeOut(1000);
}, 1000);
},
displayTime: function () {
var minutes = Math.floor(this.secondsRemaining / 60);
var seconds = this.secondsRemaining - (minutes * 60);
if (seconds < 10) seconds = "0" + seconds;
var time = minutes + ":" + seconds;
this.$('#timer').html(time);
},
});
var clock_view = new ClockView();

Titanium Appcelerator HTTPClient return Array

i want to put the httpclient in a separate class and want to return the array of founded data.
My Code
function ServiceRequest(callback){
var data = [];
var xhr = Titanium.Network.createHTTPClient({
onload: function(e){
//Ti.API.info("Received text: " + this.responseText);
var doc = this.responseXML.documentElement;
var elements = doc.getElementsByTagName("record");
for (var r=0;r<elements.length;r++){
var name = elements.item(r).getElementsByTagName("field").item(3).textContent;
var monteur = elements.item(r).getElementsByTagName("field").item(15).textContent;
var adresse =elements.item(r).getElementsByTagName("field").item(10).textContent;
var ort = elements.item(r).getElementsByTagName("field").item(4).textContent +" - "+ elements.item(r).getElementsByTagName("field").item(5).textContent;
var date = elements.item(r).getElementsByTagName("field").item(8).textContent;
var termin
if (date !="") {
var arrayDate = date.split(".");
var newdate = arrayDate[1]+"."+arrayDate[0]+"."+arrayDate[2];
var temptermin = newdate +" - "+ elements.item(r).getElementsByTagName("field").item(9).textContent;
termin = temptermin;
};
data.push({"name":name,"monteur":monteur,"adresse":adresse,"ort":ort,"termin":termin});
callback( data );
};
},
onerror: function(e){
Ti.API.debug(e.error);
alert(e.error);
}
});
xhr.open("GET","http://theurltomyxml.com",false);
xhr.send();
}
module.exports =ServiceRequest;
the code snippet for my initialization
var ServiceRequest = require('ui/common/ServiceRequest');
request = new ServiceRequest(function(data){
});
Ti.API.info(request);
But the request is null, the array in my onLoad function is filled with data.
How can i wait until the httpRequest is ready than return the data array ?
You can use your custom function for callback like this way onload : callBack create your own callback function or you can put your callback( data ); after your forloop.
for (var r=0;r<elements.length;r++){//==your code here for parsing
}
callback( data );

Resources