Javascript context within a function - javascript

I am binding a function to an event.
$('div.my_div').bind("mouseenter", timerFunc);
The problem that I have is that my context changes and I cannot access my elements. I must admit that javascript context is terribly confusing to me:
function timerFunc() {
//alert('Square ' + $(this).attr('data-somevalue') + ' named function called!');
var count_to = 10;
var count = 0;
var countup = setInterval(function () {
count++;
$(this).find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square
//self.find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square
if (count == count_to) {
count = 0;
}
}, 750);
}
Please help

Store $(this) in a variable and use it in your nested function:
function timerFunc() {
//alert('Square ' + $(this).attr('data-somevalue') + ' named function called!');
var elem = $(this);//$(this) is stored in elem variable
var count_to = 10;
var count = 0;
var countup = setInterval(function () {
count++;
//so you can use it here in nested function
elem.find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square
//self.find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square
if (count == count_to) {
count = 0;
}
}, 750);
}

setInterval executes in global context that is window, so this is window. So cache the variable and use it instead
var that = this;
var countup = setInterval(function () {
count++;
$(that).find('.countup').html(count + ' seconds!');
if(count == count_to) {
count = 0;
}
}, 750);

Related

How do I make A and B run in parallel?

How do I make A and B run in parallel?
async function runAsync(funcName)
{
console.log(' Start=' + funcName.name);
funcName();
console.log(' End===' + funcName.name)
};
function A()
{
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 1000)
i++;
console.log(' A i= ' + i) ;
}
function B()
{
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 1000)
i++;
console.log(' B i= ' + i) ;
}
runAsync(A);
runAsync(B);
The console shows that A starts first and B starts after A:
Start=A
A i= 6515045
End===A
Start=B
B i= 6678877
End===B
Note:
I am trying to use async for Chrome/Firefox, and keep the JS code compatible with IE11.
This C# code generates the proxy function runAsync:
if (isEI())
Current.Response.Write(" function runAsync(funcName){ setImmediate(funcName); }; ");
else
Current.Response.Write(" async function runAsync(funcName){ funcName(); } ");
https://jsfiddle.net/NickU/n2huzfxj/28/
Update.
My goal was to parse information and prepare (indexing and adding triggers) for an immediate response after user input. While the user is viewing the information, the background function has 3-10 seconds to execute, and the background function should not block UI and mouse and keyboard responses. Here is the solution for all browsers, including IE11.
Created a new Plugin to simulate parallel execution of funcRun during idle times.
Example of an original code:
$("input[name$='xxx'],...").each( function(){runForThis(this)}, ticksToRun );
The updated code using the Plugin:
$(document).zParallel({
name: "Example",
selectorToRun: "input[name$='xxx'],...",
funcRun: runForThis
});
Plugin.
(function ($)
{
// Plugin zParallel
function zParallel(options)
{
var self = this;
self.defaults = {
selectorToRun: null,
funcRun: null,
afterEnd: null,
lengthToRun: 0,
iterScheduled: 0,
ticksToRun: 50,
showDebugInfo: true
};
self.opts = $.extend({}, self.defaults, options);
}
zParallel.prototype = {
init: function ()
{
var self = this;
var selector = $(self.opts.selectorToRun);
self.lengthToRun = selector.length;
if (self.lengthToRun > 0)
{
self.arrayOfThis = new Array;
selector.each(function ()
{
self.arrayOfThis.push(this);
});
self.arrayOfThis.reverse();
self.opts.iterScheduled = 0;
self.whenStarted = Date.now();
self.run();
return true;
}
else
{
this.out('zParallel: selector is empty');
return false;
}
},
run: function ()
{
var self = this;
var nextTicks = Date.now() + self.opts.ticksToRun;
var _debug = self.opts.showDebugInfo;
if (self.opts.iterScheduled === 0)
{
nextTicks -= (self.opts.ticksToRun + 1); // Goto to Scheduling run
}
var count = 0;
var comOut = "";
while ((self.lengthToRun = self.arrayOfThis.length) > 0)
{
var curTicks = Date.now();
if (_debug)
{
comOut = self.opts.name + " |" + (curTicks - self.whenStarted)/1000 + "s| ";
if (self.opts.iterScheduled === 0)
this.out("START " + comOut + " remaining #" + self.lengthToRun);
}
if (curTicks > nextTicks)
{
self.opts.iterScheduled++;
if ('requestIdleCallback' in window)
{
if (_debug)
this.out(comOut + "requestIdleCallback , remaining #" + self.lengthToRun + " executed: #" + count);
window.requestIdleCallback(function () { self.run() }, { timeout: 1000 });
} else
{
if (_debug)
this.out(comOut + "setTimeout, remaining #" + self.lengthToRun + " executed: #" + count);
setTimeout(function (self) { self.run()}, 10, self);
}
return true;
}
var nexThis = self.arrayOfThis.pop();
self.opts.funcRun(nexThis);
count++;
}
if (self.opts.afterEnd!== null)
self.opts.afterEnd();
if (_debug)
this.out("END " + comOut + " executed: #" + count);
return true;
},
out: function (str)
{
if (typeof console !== 'undefined')
console.log(str);
}
};
$.fn.zParallel = function (options)
{
var rev = new zParallel(options);
rev.init();
};
})(jQuery);
// Examples.
(function ($)
{
var tab1 = $('#tbl1');
for (i = 0; i < 1000; i++)
$("<tr>"+
"<td>#" + i + "</td>"+
"<td><input id='a_" + i + "' value='" + i + "' >"+
"</td><td><input id='b_" + i + "' value='" + i + "' ></td></tr>")
.appendTo(tab1);
$(document).zParallel({
name: "A",
selectorToRun: "input[id^='a_']",
funcRun: function (nextThis)
{
var $this = $(nextThis);
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 2)
i++;
$this.val( i );
if (i > 100)
$this.css('color', 'green').css('font-weight', 'bold');
else
$this.css('color', 'blue');
}
});
$(document).zParallel({
name: "B",
selectorToRun: "input[id^='b_']",
funcRun: function (nextThis)
{
var $this = $(nextThis);
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 2)
i++;
$this.val( i );
if (i > 100)
$this.css('background', '#BBFFBB');
else
$this.css('background', '#FFBBBB');
}
});
})(jQuery);
https://jsfiddle.net/NickU/1xt8L7co/59/
The two example functions simply execute synchronously one after the other on the same "thread" (JS effectively has only one thread available to such scripts).
The use of async is irrelevant here because no truly asynchronous operation is occurring in function A - it is simply a busy while loop - so it completes in full before execution can move to anything else.
If function A had called an actual asynchronous operation (such as a HTTP request - not simply a synchronous operation wrapped in an async function), then function B may have a chance to start up (in which case B would complete entirely before the execution returned to A, because B is also only contains a synchronous, busy while loop).
Parallel processing can be achieved with WebWorkers which allowing running on background threads (actual separate threads).

How to loop a function in Javascript?

I am trying to create a countdown with JQuery. I have different times in an array. When the first time ist finished, the countdown should count to the next time in the array.
I try to do this with the JQuery countdown plugin:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
while (i < time.length) {
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
i++;
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
This does not work... But how can i do this?
You should never use a busy wait especially not in the browser.
Try something like this:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
var $counter = $("#countdown");
function countdown() {
var goal = date + " " + time[i];
$counter.countdown(goal, function(event) {
if (event.elapsed) {
i++;
if (i < time.length) {
countdown();
}
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
You can't use while or for loop in this case, because the operation you want to perform is not synchronous.
You could do for example something like this with the helper (anonynous) function:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
(function countdown(i) {
if (i === time.length) return;
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
countdown(i++);
} else {
$(this).text(event.strftime('%H:%M:%S'));
}
});
})(0)
You need to restart the countdown when the previous one finishes, at the minute you're starting them all at the same time.
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
function startCountdown(i) {
if(i >= i.length) {
return;
}
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
startCountdown(i++);
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
startCountdown(0);

How to implement codepen jquery script in wordpress?

I am trying to implement a fancy slider from codepen in wordpress. I have correctly added the script using the enqueue script method. I know I did it coorectly because it worked for a very small experiment I tried. Now the pen is: http://codepen.io/suez/pen/wMMgXp .
(function() {
var $$ = function(selector, context) {
var context = context || document;
var elements = context.querySelectorAll(selector);
return [].slice.call(elements);
};
function _fncSliderInit($slider, options) {
var prefix = ".fnc-";
var $slider = $slider;
var $slidesCont = $slider.querySelector(prefix + "slider__slides");
var $slides = $$(prefix + "slide", $slider);
var $controls = $$(prefix + "nav__control", $slider);
var $controlsBgs = $$(prefix + "nav__bg", $slider);
var $progressAS = $$(prefix + "nav__control-progress", $slider);
var numOfSlides = $slides.length;
var curSlide = 1;
var sliding = false;
var slidingAT = +parseFloat(getComputedStyle($slidesCont)["transition-duration"]) * 1000;
var slidingDelay = +parseFloat(getComputedStyle($slidesCont)["transition-delay"]) * 1000;
var autoSlidingActive = false;
var autoSlidingTO;
var autoSlidingDelay = 5000; // default autosliding delay value
var autoSlidingBlocked = false;
var $activeSlide;
var $activeControlsBg;
var $prevControl;
function setIDs() {
$slides.forEach(function($slide, index) {
$slide.classList.add("fnc-slide-" + (index + 1));
});
$controls.forEach(function($control, index) {
$control.setAttribute("data-slide", index + 1);
$control.classList.add("fnc-nav__control-" + (index + 1));
});
$controlsBgs.forEach(function($bg, index) {
$bg.classList.add("fnc-nav__bg-" + (index + 1));
});
};
setIDs();
function afterSlidingHandler() {
$slider.querySelector(".m--previous-slide").classList.remove("m--active-slide", "m--previous-slide");
$slider.querySelector(".m--previous-nav-bg").classList.remove("m--active-nav-bg", "m--previous-nav-bg");
$activeSlide.classList.remove("m--before-sliding");
$activeControlsBg.classList.remove("m--nav-bg-before");
$prevControl.classList.remove("m--prev-control");
$prevControl.classList.add("m--reset-progress");
var triggerLayout = $prevControl.offsetTop;
$prevControl.classList.remove("m--reset-progress");
sliding = false;
var layoutTrigger = $slider.offsetTop;
if (autoSlidingActive && !autoSlidingBlocked) {
setAutoslidingTO();
}
};
function performSliding(slideID) {
if (sliding) return;
sliding = true;
window.clearTimeout(autoSlidingTO);
curSlide = slideID;
$prevControl = $slider.querySelector(".m--active-control");
$prevControl.classList.remove("m--active-control");
$prevControl.classList.add("m--prev-control");
$slider.querySelector(prefix + "nav__control-" + slideID).classList.add("m--active-control");
$activeSlide = $slider.querySelector(prefix + "slide-" + slideID);
$activeControlsBg = $slider.querySelector(prefix + "nav__bg-" + slideID);
$slider.querySelector(".m--active-slide").classList.add("m--previous-slide");
$slider.querySelector(".m--active-nav-bg").classList.add("m--previous-nav-bg");
$activeSlide.classList.add("m--before-sliding");
$activeControlsBg.classList.add("m--nav-bg-before");
var layoutTrigger = $activeSlide.offsetTop;
$activeSlide.classList.add("m--active-slide");
$activeControlsBg.classList.add("m--active-nav-bg");
setTimeout(afterSlidingHandler, slidingAT + slidingDelay);
};
function controlClickHandler() {
if (sliding) return;
if (this.classList.contains("m--active-control")) return;
if (options.blockASafterClick) {
autoSlidingBlocked = true;
$slider.classList.add("m--autosliding-blocked");
}
var slideID = +this.getAttribute("data-slide");
performSliding(slideID);
};
$controls.forEach(function($control) {
$control.addEventListener("click", controlClickHandler);
});
function setAutoslidingTO() {
window.clearTimeout(autoSlidingTO);
var delay = +options.autoSlidingDelay || autoSlidingDelay;
curSlide++;
if (curSlide > numOfSlides) curSlide = 1;
autoSlidingTO = setTimeout(function() {
performSliding(curSlide);
}, delay);
};
if (options.autoSliding || +options.autoSlidingDelay > 0) {
if (options.autoSliding === false) return;
autoSlidingActive = true;
setAutoslidingTO();
$slider.classList.add("m--with-autosliding");
var triggerLayout = $slider.offsetTop;
var delay = +options.autoSlidingDelay || autoSlidingDelay;
delay += slidingDelay + slidingAT;
$progressAS.forEach(function($progress) {
$progress.style.transition = "transform " + (delay / 1000) + "s";
});
}
$slider.querySelector(".fnc-nav__control:first-child").classList.add("m--active-control");
};
var fncSlider = function(sliderSelector, options) {
var $sliders = $$(sliderSelector);
$sliders.forEach(function($slider) {
_fncSliderInit($slider, options);
});
};
window.fncSlider = fncSlider;
}());
/* not part of the slider scripts */
/* Slider initialization
options:
autoSliding - boolean
autoSlidingDelay - delay in ms. If audoSliding is on and no value provided, default value is 5000
blockASafterClick - boolean. If user clicked any sliding control, autosliding won't start again
*/
fncSlider(".example-slider", {autoSlidingDelay: 4000});
var $demoCont = document.querySelector(".demo-cont");
[].slice.call(document.querySelectorAll(".fnc-slide__action-btn")).forEach(function($btn) {
$btn.addEventListener("click", function() {
$demoCont.classList.toggle("credits-active");
});
});
document.querySelector(".demo-cont__credits-close").addEventListener("click", function() {
$demoCont.classList.remove("credits-active");
});
document.querySelector(".js-activate-global-blending").addEventListener("click", function() {
document.querySelector(".example-slider").classList.toggle("m--global-blending-active");
});
The javascript code can e found above and in the mentioned link.I know that in wordpress we have to use jQuery in place of $ but I still can't seem to figure out how to do it in this case. And one more thing, the css is in scass form but I have taken the compiled css form but I don't think that is causing any problem (rignt?) Everything I have tried till this point has failed. Any help will be appreciated
You can use $ instead of jQuery in WordPress so long as you wrap all your code inside the following:
(function($) {
// Your code goes here
})( jQuery );
If the code is in the header (before the document is ready) then instead use:
jQuery(document).ready(function( $ ) {
// Your code goes here
});
If your code is still having problems, then please include both the enqueue code in your theme and the error messages

Return value inside a setInterval

I want to return a value inside a setInterval. I just want to execute something with time interval and here's what I've tried:
function git(limit) {
var i = 0;
var git = setInterval(function () {
console.log(i);
if (i === limit - 1) {
clearInterval(git);
return 'done';
}
i++;
}, 800);
}
var x = git(5);
console.log(x);
And it's not working.
Is there any other way?
What I'm going to do with this is to do an animation for specific time interval. Then when i reached the limit (ex. 5x blink by $().fadeOut().fadeIn()), I want to return a value.
This is the application:
function func_a(limit) {
var i = 0;
var defer = $.Deferred();
var x = setInterval(function () {
$('#output').append('A Running Function ' + i + '<br />');
if (i == limit) {
$('#output').append('A Done Function A:' + i + '<br /><br />');
clearInterval(x);
defer.resolve('B');
}
i++;
}, 500);
return defer;
}
function func_b(limit) {
var c = 0;
var defer = $.Deferred();
var y = setInterval(function () {
$('#output').append('B Running Function ' + c + '<br />');
if (c == limit) {
$('#output').append('B Done Function B:' + c + '<br /><br />');
clearInterval(y);
defer.resolve('A');
}
c++;
}, 500);
return defer;
}
func_a(3).then( func_b(5) ).then( func_a(2) );
This is not functioning well, it should print A,A,A,Done A,B,B,B,B,B,Done B,A,A,Done A but here it is scrambled and seems the defer runs all function not one after the other but simultaneously. That's why I asked this question because I want to return return defer; inside my if...
if (i == limit) {
$('#output').append('A Done Function A:' + i + '<br /><br />');
clearInterval(x);
defer.resolve('B');
// planning to put return here instead below but this is not working
return defer;
}
Do you expect it to wait until the interval ends? That would be a real pain for the runtime, you would block the whole page. Lots of thing in JS are asynchronous these days so you have to use callback, promise or something like that:
function git(limit, callback) {
var i = 0;
var git = setInterval(function () {
console.log(i);
if (i === limit - 1) {
clearInterval(git);
callback('done');
}
i++;
}, 800);
}
git(5, function (x) {
console.log(x);
});
Using a promise it would look like this:
function git(limit, callback) {
var i = 0;
return new Promise(function (resolve) {
var git = setInterval(function () {
console.log(i);
if (i === limit - 1) {
clearInterval(git);
resolve('done');
}
i++;
}, 800);
});
}
git(5)
.then(function (x) {
console.log(x);
return new Promise(function (resolve) {
setTimeout(function () { resolve("hello"); }, 1000);
});
})
.then(function (y) {
console.log(y); // "hello" after 1000 milliseconds
});
Edit: Added pseudo-example for promise creation
Edit 2: Using two promises
Edit 3: Fix promise.resolve
Try to get a callback to your git function.
function git(limit,callback) {
var i = 0;
var git = setInterval(function () {
console.log(i);
if (i === limit - 1) {
clearInterval(git);
callback('done') // now call the callback function with 'done'
}
i++;
}, 800);
}
var x = git(5,console.log); // you passed the function you want to execute in second paramenter

How to reference a setInterval() id from itself in JavaScript, without help of an outer scope?

Just out of curiosity: can I reference a setInterval() id from itself, without having to store itself in a variable?
So, instead of doing this:
function counter() {
console.log(id + ": " + count++);
if (count > 10)
clearInterval(id);
}
var count = 0;
var id = setInterval(counter, 250);
I'd be doing this:
function counter() {
console.log(aReferenceToItsOwnId + ": " + count++);
if (count > 10)
clearInterval(aReferenceToItsOwnId);
}
var count = 0;
setInterval(counter, 250);
Which would, just in example, allow me to reuse the function simply, like this:
setInterval(counter, 200);
setInterval(counter, 250);
setInterval(counter, 333);
No, you can't. The only place accessible to your code that the id is tracked is the return value of the setInterval function.
If you want to reuse the function, you could wrap it like:
function startCounter(time) {
function counter() { ... }
var count = 0;
var id = setInterval(counter, time);
}
startCounter(200);
startCounter(250);
startCounter(333);
Use additional parameter of function to do this.
var si1=setInterval(function(){counter(1);},200);
var si2=setInterval(function(){counter(2);},250);
var si3=setInterval(function(){counter(3);},333);
function counter(id)
{
...
clearInterval(window['si'+id]);
...
}
As the other answers state, it is impossible. However, you could create a helper function to greatly ease that fact.
Code
function timer(callback, interval) {
var id = setInterval(function() {
callback.call({ id: id });
}, interval);
};
Usage
var count = 0;
function counter() {
console.log(this.id + ' - ' + count++);
if (count > 10) clearInterval(this.id);
};
timer(counter, 250);
timer(counter, 300);

Categories