How to add call back function for this code? - javascript

I wondered what is the most easy way to add call back function to the function below:
<script>
$(document).on('focus', '#inputbox', function(e) {
$( this).contents().filter(function() {
return this.nodeType === 3;
}).wrap("<span class='new'></span>");
//I tried add function here but it would execute infinite times.
});
</script>

The same you already try, but skip all redundant calls for cb
<script>
function cb() { alert('Wow!'); }
(function() {
var timer;
var delay = 1000; // call cb delay
$(document).on('focus', '#inputbox', function(e) {
$( this).contents().filter(function() {
return this.nodeType === 3;
}).wrap("<span class='new'></span>");
clearTimeout(timer);
timer = setTimeout(cb, delay);
});
})();
</script>

Related

Unable to reset setTimeout timer in JavaScript

Here is my pseudocode:
if(key.pressed = 'a') {
activate = true;
}
var mytimeout = function timer_function() {
// Do stuff;
setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(mytimeout);
timer_function();
}
}
if(mouse.click == true) {
some_function();
}
I want the timer to be reset on each mouse click which calls some_function(). What actually happens is that the time is set on first click but never resets after that.
What am I missing?
Thanks.
mytimeout is a function, not a timeout handle. What you need to store is the result of the setTimeout call like this.
var timeoutHandle;
function timer_function() {
// Do stuff;
timeoutHandle = setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(timeoutHandle);
timer_function();
}
}
In function timer_function return the value of setTimeout
var mytimeout = function timer_function() {
return setTimeout( function() {
//Do some more stuff
}, 5000);
}
Thats because in you are only going to replay the Timeout only when the user presses the "a" key. I don't know why you kept it like that but thats probably the reason.!

Run JS code when user finished typing

I have a lot of input fields with the same class. When the user finishes typing the function doneTyping should run.
I tried this but somehow it doesn't work.
Can I use one function for all the input fields I have?
$(function() {
console.log('ready');
var timer;
var doneTypingInt = 5000;
$('.typing').keyup(function(){
clearTimeout(timer);
if ($('.typing').val()) {
timer = setTimeout(doneTyping, doneTypingInt);
}
});
function doneTyping () {
console.log('function doneTyping');
}
});
what you're looking for is debounce
$('.typing').keypress(_.debounce(yourfunc, 3000))
You basically want to use the keypress function. Your adjusted code:
$(function() {
console.log('ready');
var timer;
var doneTypingInt = 5000;
$('.typing').keypress(function(event){
if(timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(doneTyping, doneTypingInt);
});
function doneTyping () {
console.log('function doneTyping');
}
});
I don't think that you have something wrong in your code, you just have to wait 5 seconds to see the result, and in order to use one function for all inputs with the "typing" class, you should use the bind method as follows:
Javascript code: (Jsfiddle)
$(function() {
console.log('ready');
var timer;
var doneTypingInt = 1000;
$('.typing').keyup(function(){
clearTimeout(timer);
if ($('.typing').val()) {
timer = setTimeout(doneTyping.bind($(this)), doneTypingInt);
}
});
function doneTyping () {
alert('function doneTyping ' + this.val());
}
});

Dynamically added function still running even after remove from DOM

This script has been added dynamically. It has a timeout function, means that it runs every 5 seconds.
dynamicjs.php
$(document).ready(function(){
(function( $ ){
$.fn.baslatmesajlari = function() {
setInterval(function(){
console.log("I am running");
}, 5000);
return this;
};
})( jQuery );
});
$("body").baslatmesajlari();
I load this function to a div using;
$("#temporarycontent").load("dynamicjs.php");
And when I do
$("#temporarycontent").empty();
The script is still running. How can I stop it run ?
You can't, you need a handle to the intervalId returned by the setInterval function or provide an API on the plugin in order to destroy it and cleanup after itself. The easiest way would be to attach the state of the plugin to the DOM element on which it was applied.
(function ($) {
const PLUGIN_NAME = 'baslatmesajlari';
function Plugin($el) {
this.$el = $el;
this._timerId = setInterval(function () {
console.log('running');
}, 2000);
}
Plugin.prototype.destroy = function () {
this.$el.removeData(PLUGIN_NAME);
clearInterval(this._timerId);
};
$.fn[PLUGIN_NAME] = function () {
if (!this.data(PLUGIN_NAME)) this.data(PLUGIN_NAME, new Plugin(this));
return this;
};
})(jQuery);
$(function () {
var plugin = $('#plugin').baslatmesajlari().data('baslatmesajlari');
$('#destroy').click(function () {
plugin.destroy();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="plugin"></div>
<button id="destroy">Destroy plugin</button>
You must have a reference to the interval id, then, when you want to stop it's execution, call clearInterval(the_id)
let interval = null //this is the variable which will hold the setInterval id
$(document).ready(function () {
(function ($) {
$.fn.baslatmesajlari = function() {
interval = setInterval(function () {
console.log('I am running')
}, 5000)
return this
}
})(jQuery)
})
$("body").baslatmesajlari()
And then:
$("#temporarycontent").empty();
clearInterval(interval) // it should stop the function.
Hope it helps.

JQuery merge two functions keyup and focusout

On a form-field I work with two active functions: keyup and focusout.
The functions execute the same code, only the key-up uses a delay-function.
Function for delay:
$(function() {
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Functions for keyup and focusout:
$("#name").on('keyup', function (){
var textn = $(this).val();
var nbrCharn = textn.length;
delay(function(){
if(nbrCharn > '2'){ $('#nameMsg').html('Nice.');
}else { $('#nameMsg').html(''); }
}, 1000 );
});
$("#name").on('focusout', function (){
var textn = $(this).val();
var nbrCharn = textn.length;
if(nbrCharn > '2'){ $('#nameMsg').html('Nice.');
}else { $('#nameMsg').html(''); }
});
The keyup needs the delay, the focusout does not.
This code works fine, but is it possible to merge those functions, so I don't have the same code twice?
you could define a handler that takes an argument which is a completion function
var handler = function (completion){
return function(){
var textn = $(this).val(),
nbrCharn = textn.length;
completion(function(){
if(nbrCharn > '2'){
$('#nameMsg').html('Nice.');
} else {
$('#nameMsg').html('');
}
});
};
};
and then define the handlers
$("#name").on('keyup',handler(function(cb){delay(cb,1000);}));
$("#name").on('focusout',handler(function(cb){cb();}));
If you use several events in one handler use the event object argument to check event.type
$("#name").on('keyup focusout', function (evt){
if(evt.type === 'keyup'){
/* keyup only code */
}
});
Or something like
var delay = evt.type === 'keyup' ? 0 :1000;
then use delay() for both
You could try passing the relevant jquery this object to a function:
var delay =
(function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
}
)()
$(document).ready(init);
function init() {
$("#name").on('keyup', function (){
var self = this;
delay(
(function(self){
return function(){
writeNameMsg(self)
};
})(self)
, 1000 );
});
$("#name").on('focusout', function (){
writeNameMsg(this);
});
}
function writeNameMsg(self){
var textn = $(self).val();
var nbrCharn = textn.length;
if(nbrCharn > '2'){
$('#nameMsg').html('Nice.');
} else {
$('#nameMsg').html(''); }
}
};
One straightforward way is to .trigger() one event from the other after a delay:
$("#name").on('keyup', function (){
var $this = $(this);
setTimeout(function() {
$this.trigger('focusout');
}, 1000); // milliseconds
});
Alternatively, use an external callback function for both, using .call() to pass along the same element as this:
$("#name").on('keyup', function() {
var el = this;
setTimeout(function() { callbackFunc.call(el) }, 1000); // milliseconds
});
$("#name").on('focusout', callbackFunc);

Run a function after each function

For some reason, I can't get a function to run after the each function is complete. This is what I tried and the each function works perfectly but it does not run the other function when it is complete.
var delay = 0;
$('h1 span').each(function() {
var $span = $(this);
setTimeout(function() { $span.addClass('visible'); }, delay+=1000, function(){
$('header').addClass('visible');
});
});
If i understand your expected behaviour, you can use following logic inside delayed function:
var delay = 0;
$('h1 span').each(function () {
var $span = $(this);
setTimeout(function () {
$span.addClass('visible');
// if $span is last of 'h1 span' matched set
if ($span.is($('h1 span').last())) {
$('header').addClass('visible');
}
}, delay += 1000);
});
-DEMO-
I think what you want to do is this http://jsfiddle.net/gon250/8mdodywe/
setTimeout() function doesn't support two callbacks.
$.when($('span').each(function() {
$(this).addClass('visible');
})).then(function(){
$('header').addClass('visible');
});
I guess that's what you want:
var delay = 0;
$('h1 span').each(function() {
var $span = $(this);
setTimeout(function() { $span.addClass('visible'); }, delay+=1000);
});
setTimeout(function() { $('header').addClass('visible'); }, delay);
Check it out: http://jsfiddle.net/zsm4xegr/
I'm assuming, you want two timeouts? From your Code it seems you would like to execute the first timeout after "delay 0". In that case simply execute the first "callback" and set a timout for the second.
If you do indeed want two timeouts (each after 1000ms):
$('h1 span').each(function() {
var $span = $(this);
setTimeout(
function() {
$span.addClass('visible');
setTimeout(
function() {
$('header').addClass('visible');
},
1000
);
},
1000
);
});

Categories

Resources