Javascript timer that restarts on key up? - javascript

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 :)

Related

How to find JS function name?

I have implemented on a website a picture gallery that does not allow (it seems) the auto sliding. So at the moment I have to push on a button to see the next picture. My purpose is to catch the function that allows to move to the next picture and to set a timeout to go to the next picture automatically.
How can I get the JS function name using Google Chrome developer tools?
Thank you
UPDATE
This is the Gallery script: http://tympanus.net/Development/ScatteredPolaroidsGallery/
I would like to implement auto sliding on it
source for code proposal from: https://github.com/codrops/ScatteredPolaroidsGallery/issues/4
(function() {
function autoSliding(timeout) {
var self = this;
clearTimeout(self.timeOut);
self.timeOut = setTimeout(function() {
self._navigate('next');
}, timeout);
}
new Photostack( document.getElementById( 'photostack-1' ), {
afterShowPhoto: function(context) {
autoSliding.call(context, 3000)
},
afterNavigate: function(context) {
autoSliding.call(context, 3000)
}
});
new Photostack( document.getElementById( 'photostack-2' ), {
afterShowPhoto: function(context) {
autoSliding.call(context, 3000)
},
afterNavigate: function(context) {
autoSliding.call(context, 3000)
}
});
}())
This should do the work
$('.navigate-next').click();
Or for auto scroll
setInterval(function(){$('.navigate-next').click();},1000);
Change 1000 for whatever you wish
If you are allowed to use jquery in your code, then, you can use $._data() method.
syntax is $._data($("selector of the element")[0], "events")
This will return an Object of all events bounded to that element. Then get the click event and call the handler attribute of the click event.

jQuery fade in and fade out loop issue

I am making a results screen which toggles between showing the user their best time/score and their latest time/score. I found a solution using this site but after leaving the website open for a few hours I saw that the timings had gone out of sync. I know that this is hard to test so I thought I would see if any experts on here could help me to optimize or fix my code.
CODEPEN
JSFIDDLE
JS
$(document).ready(function() {
setInterval( function() { resultsTransition(); }, 4000);
function resultsTransition() {
$('.latest-transition').fadeOut(500).delay(3500).fadeIn(500).delay(3500);
$('.best-transition').fadeIn(500).delay(3500).fadeOut(500).delay(3500);
}
});
I think your design could be improved (and the out-of-sync problem solved) by simply toggling the opacity of the elements in your resultsTransition method instead of starting a new sequence, which could interfere unpredictably with the interval.
Something like:
var latestTransitionElementVisible = true; //the initial state of your elements
setInterval(resultsTransition, 4000); //note you can just pass the function name
function resultsTransition() {
$('.latest-transition').fadeTo(500, latestTransitionElementVisible ? 0 : 1);
$('.best-transition').fadeTo(500, latestTransitionElementVisible ? 1 : 0);
latestTransitionElementVisible = !latestTransitionElementVisible ;
}
I guess whatever problem/issue you are facing is because of varying animation times .Try the following:
$(document).ready(function() {
setTimeout( function() { resultsTransition(); }, 4000);
function resultsTransition() {
if(!$('.latest-transition').is(':animated') && !$('.best-transition').is(':animated'))
{
$('.latest-transition').fadeOut(500).delay(3500).fadeIn(500).delay(3500);
$('.best-transition').fadeIn(500).delay(3500).fadeOut(500).delay(3500);
setTimeout( function() { resultsTransition(); }, 4000);
}
}
});

setTimeout/pausing/ etc

I've tried a few different ways except the right one.
Trying this:
setTimeout( function() {
$('.historyTextBoxes p')
.bind('showText', function(e) {
$(this).fadeIn(800, function(){
$(this).next().length && $(this).next().trigger("showText");
});
}).eq(0).trigger('showText');
}, 4000);
Will wait for 4 seconds, then fade each paragraph in, one after another at the speed of .800 miliseconds.
What I want to do is fade a paragraph in at .800 ms, then wait for 4 seconds before the next paragraph fades in.
The basic set-up of:
$('.historyTextBoxes p')
.bind('showText', function(e) {
$(this).fadeIn(800, function(){
$(this).next().length && $(this).next().trigger("showText");
alert('pause here');
});
}).eq(0).trigger('showText');
works but I've yet to hit the right syntax to make it pause where the alert is.
I tried throwing a call to a function but I don't need to run anything except just to wait.
So in pseudo code, I'm trying to define something like:
function wait() {
pause(for 4 seconds);
}
Then I could just call that function instead of the alert above. My issues with setTimeout has been 'having' to define a function but I'm over thinking something.
Using setTimeout was correct, but you applied it in the wrong place.
$('.historyTextBoxes p').bind('showText',function(e) {
$(this).fadeIn(800,function(){
// this is the callback after the fadein
// here we want to wait (use a timeout)
var next = $(this).next();
if (next.length)
setTimeout(function() {
// before the next text is shown
next.trigger("showText");
}, 4000);
})
}).eq(0).trigger('showText');
This should do it:
function showAll() {
var p = $('.historyTextBoxes p').get(); // array of elements
(function loop() {
if (p.length) {
var el = p.shift();
$(el).fadeIn(800).delay(4000).promise().done(loop);
}
})();
}
demo at http://jsfiddle.net/4dNr3/2/
Note that this uses no explicit timers at all, and nor does it use any events to trigger the next phase - it relies on the animation queue for all timing. Note that it's not generally a good idea to mix timers and animation unless you can guarantee that they're interleaved rather than running in parallel. In this case that's OK, though.

Change reload interval to waiting after the last reload

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 :)

Fire javascript (lightbox) once per session

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;
}

Categories