My application reloads data every 500ms. How do I have to change the code to not reload every 500ms but to wait for 500ms after the last reload to trigger a new one?
App = Ember.Application.create({
ready: function() {
var switchboard = App.Switchboard.find(switchboard_id);
setInterval(function() {
switchboard.reload();
}, 500);
}
});
I have just done something similar. You should use activate property on your route (http://emberjs.com/api/classes/Ember.Route.html#method_activate).
Checkout this pull request: https://github.com/chrmod/rowmark/pull/2/files
Some example:
App.NoteRoute = Ember.Route.extend({
activate: function() {
this.interval = setInterval(function() {
this.get('controller').set('toSave', true);
}.bind(this), 5000);
}
})
UPDATE
I understand you wrong. Sorry for that.
First of all you need to know that find from Ember Model or Ember Data returns promises (http://emberjs.com/blog/2013/05/28/ember-data-0-13.html)
I think you can do such trick to implement that:
App = Ember.Application.create({
ready: function() {
var switchboard;
setInterval(function() {
switchboard = App.Switchboard.find(switchboard_id).then(function(){
setTimeout(function(){}, 499);
});
}, 1);
}
});
First of all we run setInterval to run this in infinity loop. Next in each loop iteration we find Switchboard and when Ember data loads from external server those data that run function that is passed to then. This function simply wait 499ms :)
Related
i have tried using angularjs and jquery for developing my websites and i'm not new to them. but somehow i stumbled to an issue which is not so familiar for me.
the main problem is between angular routing and jquery document ready script execution.
the scenario is i use angularjs ui-router to browse pages for my website(SPA) one of my page has inline jquery codes looks like this
<div id="details-page">
</div>
<script>
var counter = 0;
function foo() {
var setFoo = setInterval(function() {
counter++;
console.log(counter);
}, 2000);
}
</script>
foo();
the codes runs as expected,
but when i go route to another pages i can see my logs still running(the foo function) which seems weird for me but that's not the main problem, the main problem is when i go back to "details-page" the function foo is executed back(because of $(document).ready(function(){})) so two foo's is running in my system which is definitely destroyed everything.
so my goal here is how to STOP the old foo function or
how to STOP the new function foo from executing in short i just want one foo function running in my system, thanks
If I understand you correctly you want this counter to start when the user enters the "details-page", you want it to keep running when they leave, and when they come back it must use the original counter.
To solve this with AngularJS you should create a service, as your service will be a singleton and not linked specifically to the "details-page".
Fiddle example: https://jsfiddle.net/UncleDave/g9co2172/1/
angular
.module('app', [])
.controller('DetailsCtrl', function(counterService) {
counterService.start();
})
.service('counterService', function($interval) {
var counter = 0;
var started = false;
function start() {
if (started)
return;
started = true;
$interval(function() {
counter++;
console.log(counter);
}, 2000);
}
return {
start: start
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="DetailsCtrl as details">
</div>
just add this code in your controller,and don't forget t inject $rootScope and $interval services in your controller.
$rootScope.counter = 0;
var setFoo;
function foo() {
setFoo = $interval(function () {
$rootScope.counter++;
console.log($rootScope.counter);
}, 2000);
}
foo();
$rootScope.$on("$routeChangeStart", function () {
$interval.cancel(setFoo);
})
I have a jquery function I want to run ONLY when a page is loaded the first time, not after a refresh.
Here's the code:
$(window).on("load",function() {
$("#logo-black").typed({
strings: ["Nothing^450&Co^250.^500", "^800__^400&Co^600."],
typeSpeed: 70,
backSpeed: 100,
callback: function() {
$(".typed-cursor").css("display", "none"),
setTimeout(function(){
$('.main-load').toggleClass('main-load-active'),
$('.nav-text').toggleClass('nav-text-active');
},400),
$('.nav-reveal').toggleClass('nav-reveal-active');
}
});
});
A few things to note:
-I'm using barba.js, so content is added/removed via AJAX.
Code that initializes barba.js for my project:
initFullpagePlugin();
function initFullpagePlugin (parentElement) {
var element;
element = parentElement ? $('#fullpage', parentElement) :
$('#fullpage');
if (element.length) {
// Destroys old fullPage.js object in memory,
// removes elements from DOM
if ($.fn.fullpage.destroy) {
$.fn.fullpage.destroy('all');
}
element.fullpage({
//Scrolling
autoScrolling:false,
scrollingSpeed: 2500,
easing: 'swing',
fitToSection: false
});
}
}
document.addEventListener("DOMContentLoaded", function() {
if (!('webkitClipPath' in document.body.style)) {
alert('Sorry, this demo is available just with webkitClipPath. Try with
Chrome/Safari.');
}
Barba.Pjax.init();
Barba.Prefetch.init();
var FadeTransition = Barba.BaseTransition.extend({
start: function() {
/**
* This function is automatically called as soon the Transition starts
* this.newContainerLoading is a Promise for the loading of the new
container
* (Barba.js also comes with an handy Promise polyfill!)
*/
// As soon the loading is finished and the old page is faded out, let's
fade the new page
Promise
.all([this.newContainerLoading, this.fadeOut()])
.then(this.fadeIn.bind(this));
},
fadeOut: function() {
/**
* this.oldContainer is the HTMLElement of the old Container
*/
return $(this.oldContainer).animate({ opacity: 0 }).promise();
},
fadeIn: function() {
/**
* this.newContainer is the HTMLElement of the new Container
* At this stage newContainer is on the DOM (inside our #barba-
container and with visibility: hidden)
* Please note, newContainer is available just after
newContainerLoading is resolved!
*/
document.body.scrollTop = 0;
var _this = this;
var $el = $(this.newContainer);
$(this.oldContainer).hide();
$el.css({
visibility : 'visible',
opacity : 0
});
initFullpagePlugin($el);
$el.animate({ opacity: 1 }, 400, function() {
/**
* Do not forget to call .done() as soon your transition is finished!
* .done() will automatically remove from the DOM the old Container
*/
_this.done();
});
}
});
/**
* Next step, you have to tell Barba to use the new Transition
*/
Barba.Pjax.getTransition = function() {
/**
* Here you can use your own logic!
* For example you can use different Transition based on the current
page or link...
*/
return FadeTransition;
};
});
$('.no-click').on("click", function(e) {
e.preventDefault();
});
For instance, this design studio has an animation that runs when you first load the home page, but not after a refresh. (NOTE: this seems to only apply to the mobile version, but it's what I'm trying to achieve. The element I'm animating is present on every page, so making sure it only fires on first load & ONLY on the index.html is something I'm shooting for)
Any help/suggestions/constructive criticism is appreciated!
Code executed on the client is stateless between loads. If you want to remember state from page load to page load, you can either:
Track the session on the back end.
Use cookies/local storage in the client's browser.
You can easily do this from the server side.
Check the referrer header. If it is not present, or it is not the same as the URL in the current request, go ahead and emit the jquery function so that it will execute when the page is loaded into the browser. When it is the same as the URL in the current request, just withhold the jquery script so that it can't run.
If the page is 100% static and you can't do anything like this, well, see Chase's answer.
You can use the transitionCompleted function to load your script.
Barba.Dispatcher.on('transitionCompleted', function(currentStatus, prevStatus) {
if (prevStatus) {
setTimeout(function() {
// call your script
}, 1000);
}
});
Remember that the barba.js event transitionCompleted is fired each time a new page is loaded.
I have a simply counter running doRefresh() in an ionic/angular application, as you can see it is calling itself with the $interval, but when a user leaves this view. The counter is still running. I cant get it to stop running. I have tried many things including the code below. Please help. Thnk you
$interval(function () {
$scope.doRefresh();
console.log("refresh done");
}, 3000);
$scope.$on('$ionicView.enter', function(){
$scope.$on("$destroy",function(){
if (angular.isDefined($scope.doRefresh())) {
$interval.cancel($scope.doRefresh())
console.log("Destroyed");
}
});
});
$interval returns the promise you need to cancel the interval. See the following code:
var refresher = $interval(function () {
$scope.doRefresh();
console.log("refresh done");
}, 3000);
$scope.$on('$ionicView.enter', function(){
$scope.$on("$destroy",function(){
//This really wouldn't be needed, as refresher should always be defined.
if (angular.isDefined(refresher)) {
$interval.cancel(refresher);
refresher = undefined;
console.log("Destroyed");
}
});
});
Hey all I have a quick javascript question! Frustrated trying to get it sorted.... right now my modal div shows after 10 seconds which is right, but I want to only show it ONCE per session. Here's my current code:
<script type="text/javascript">
$(function() { // wait for the DOM
setTimeout(function () {
var $modal = $('#free-awesome'); // your selector; cache it; only query the DOM once!
$modal.modal('show'); // show modal; this happens after 10 seconds
setTimeout(function () {
$modal.modal('hide'); // hide modal;
}, 50000);
}, 10000);
});
</script>
Any ideas how I can adapt that javascript to show once per visit/session?
I'm quite new to javascript so if you could let me know exactly what to swap the above out for that'd be great!
Thanks in advance
You can use the session storage:
if(!sessionStorage.hidemodal) {
// your code ...
sessionStorage.hidemodal = true;
}
O, so i have a 'live search' ajax search, which currently runs an sql search (via ajax) on each key up.
What i would prefer is to:
run an sql search after a key has not been pressed for say 800 milliseconds
.
So i want to have a timer that is started on key up,
if the timer reaches 800ms then the ajax is called,
if a new keyup event occurs the timer is restarted
how would i do this?
(function () {
var theTimeout;
function doSearch() {
// Do Search
};
$('#theField').bind('keyup', function () {
clearTimeout(theTimeout);
theTimeout = setTimeout(doSearch, 800);
});
}())
There's an excellent plugin TypeWatch you may take a look at (IIRC StackOverflow uses this for the Users page). Here's a sample usage:
$("#textId").typeWatch({
highlight: true,
wait: 800,
captureLength: -1,
callback: function() {
// changed text
}
});
I had that problem my solution was this:
var doAjax = 0
$("input#name").keyup(function(){
doAjax++;
setTimeout(function(){
doAjax--;
if(doAjax>=1){
return;
}
$.post("do_ajax", { ...
dunno if it is the best solution, but it works :)