Working on my framework again. Wanted to create a method to blink an element. I would need to set interval inside the method. So I thought this might work:
var optionalSelector = "$";
(function() {
(this[arguments[0]] = function constructor(input) {
if (!(this instanceof constructor)) { return new constructor(input); }
this.elm = document.getElementById(input);
}).prototype = {
blink: function() {
function changeDisplay() {
if (this.elm.style.display != "none") {
this.elm.style.display = "none";
} else {
this.elm.style.display = "block";
}
}
setInterval(changeDisplay, 1000);
},
};
})(optionalSelector);
And calling the method $("anElmId").blink();
But it doesn't. Another function inside the method and there's also an interval. I guess this two messes things up. Like it doesn't recognize this.elm. Since I'm a newbie I couldn't figure out a way to fix this. Any ideas?
Fiddle
You should try some console.log statements in your code. When in Chrome or in Firefox (preferably with firebug plugin installed) you can press F12 to open the console and check out the output of your logs.
console.log(this)
In changeDisplay would reveal that this most likely is Window. To understand why you have to understand what this stands for in JavaScript. I like to call it the function invoking
object as that most accurately describes it (in my opinion). See here for more details.
var optionalSelector = "$";
window[optionalSelector] = function constructor(input) {
if (!(this instanceof constructor)) {
return new constructor(input);
}
this.elm = document.getElementById(input);
this.intervalid = 0;
this.timeoutid = 0;
};
window[optionalSelector].prototype.blink =
function(interval, timeout) {
this.intervalid = setInterval(this._callbacks.
changeDisplay(this.elm), interval);
this.timeoutid=setTimeout(this._callbacks.
cancelInterval(this.intervalid),timeout);
return this;
};
window[optionalSelector].prototype.cancel = function() {
clearTimeout(this.timeoutid);
clearInterval(this.intervalid);
return this;
};
// I like to have callback functions (closures) in it's own
// scope so you can better control what variables
// are passed to it
window[optionalSelector].prototype._callbacks = {
changeDisplay: function(elm) {
return function() {
if (elm.style.display !== "none") {
elm.style.display = "none";
} else {
elm.style.display = "block";
}
};
},
cancelInterval:function(intervalid){
return function(){
clearInterval(intervalid);
};
}
};
var myBlinker = window[optionalSelector]
("hplogo").blink(200, 2000);
//cancel it
myBlinker.cancel();
//blink something else for 2 seconds
window[optionalSelector]("gbqfba").blink(200, 2000);
Went to google.com pressed F12 and ran the above code. It should work. More on the difference between prototype properties and instance properties here.
Related
When I search for a function name - it gets clumsy when I see plenty of function names as in the example. In large code base I waste my time when searching for how and from where a function has been called :
function do_something()
{
if (typeof do_something.flag == "undefined")
{
do_something.flag = true;
}
if (do_something.flag == null)
{
do_something.flag = true;
}
}
Here when I search for do_something so that I can look from where it is called instead I find plenty of lines consisting of do_something.flag1,do_something.flag2 and so on which isn't of any use in most of such searches. In large function I get plenty of such lines occupying search output.
I've another scenario. In (Netbeans) IDE I want to do Ctrl-F do_something function looking for where it is called in the file. Now I find pressing F3 within the function itself iterating over it's own lines containing something like do_something.var1=5 etc.
In short is there any way to reduce the function name usage within the function when creating object-global variables?
I've much longer functions but I'll give real example of medium level function causing this problem:
function slow_down_clicks(label, userfunc, timeinmsec)
{
console.log("slow_down_clicks=" + label);
if (typeof slow_down_clicks.myobj == UNDEFINED)
{
slow_down_clicks.myobj = {};
}
if (typeof slow_down_clicks.myobj[label] == UNDEFINED)
{
slow_down_clicks.myobj[label] = {
inqueue: false,
lastclickedtime: 0,
login_post_error_count: 0
};
}
var myfunc = function ()
{
console.log("Executing the user func");
slow_down_clicks.myobj[label].inqueue = false;
slow_down_clicks.myobj[label].lastclickedtime = new Date().getTime();
userfunc();
}
console.log("Due to error in home.aspx reloading it", ++slow_down_clicks.myobj[label].login_post_error_count);
if (slow_down_clicks.myobj[label].inqueue == false)
{
var diff = new Date().getTime() - slow_down_clicks.myobj[label].lastclickedtime;
console.log("diff=", diff, timeinmsec);
if (diff > timeinmsec)
{
myfunc(); //click login
}
else
{
console.log("queuing the request after:", timeinmsec - diff);
slow_down_clicks.myobj[label].inqueue = true;
setTimeout(function ()
{
console.log("called myfunc babalatec");
myfunc();
}, timeinmsec - diff);
}
}
else
{
console.log("Discarding this request...");
}
}
I think you can just define the fields as normal variables and put your code in its own file. Then you can just refer to the variables by its name inside your function because they are within the function's closure. The variables will not be accessible outside because you limit them in its own file.
like:
let flag = false
function doSomething () {
if (!flag) {
flag = true
}
....
}
Put the above code snippet in a separate file and import the function when you want to use it.
This is the question:
Define a function named print which just print out the parameters it gets.
But it will not print out anything if it's called normally.
Only in a setTimeout callback will become effective.
e.g:
setTimeout(function() {
print('123'); //===> 123
});
print('456'); //===> nothing output
I have one solution but I don't think it's a good way, I rewrite the setTimeout.
I want a better solution curiously.
var print = function() {
'use strict';
var __origSetTimeout = window.setTimeout;
window.setTimeout = function(fn, delay) {
var _fn = new Function(`(${fn.toString().replace(/print\(/g, 'print.call(this,')}).call(this);`);
return __origSetTimeout.call(window, _fn.bind({
isFromSetTimeout: true
}), delay);
};
return function print(word) {
if (!this || !!this && !this.isFromSetTimeout) return;
console.log(word);
};
}.call(null);
You can use scope to solve this, for example
function A(){
let print = function(str){
console.log(str);
}
this.setTimeout = function(){
setTimeout(function(){
print('123');
}, 1000);
}
}
let a = new A();
a.setTimeout();
You could use a monkey patch for an extension of the print function with an additional check for a this object and a property for printing.
// simple function with output
function print(s) {
console.log(s);
}
// apply monkey patch
void function () {
var p = print;
print = function () {
if (this && this.timeout) {
p.apply(this, arguments);
}
}
}();
// bind additional information
setTimeout(print.bind({ timeout: true }, '123'));
print('456');
I've defined some functions, and I want to get user input to invoke those functions. I have the following code, but can't figure out how to invoke the actual function when I'm using a variable. I assumed below code would work..
thanks!
var someFunctions = {
play: function() {
if (player.stopped()) {
player.play();
} else {
return false;
}
}
var getCommand = function(){
var command = prompt("Please enter a command");
if (!(command in someFunctions)) {
alert('command not recognized');
getCommand();
} else {
command();
}
}
getCommand();
var someFunctions = {
play: function() {
if (player.stopped()) {
player.play();
}
else {
return false;
}
}
};
var getCommand = function(){
var commandInput = prompt("Please enter a command");
var command = someFunctions[commandInput];
if (!command) {
alert('command not recognized');
getCommand();
}
else {
command();
}
};
getCommand();
The reason your code isn't working is because you're missing the closing } of someFunctions.
var someFunctions = {
play: function() {
if (player.stopped()) {
player.play();
} else {
return false;
}
}
} // here
Your call is fine, you call a "variable" function the same way you do a regular one. The only difference between a "variable" function and an ordinary one is you can call the ordinary one before it's declared (if you're in the same scope at least)
I see different topics about the toggle function in jquery, but what is now really the best way to toggle between functions?
Is there maybe some way to do it so i don't have to garbage collect all my toggle scripts?
Some of the examples are:
var first=true;
function toggle() {
if(first) {
first= false;
// function 1
}
else {
first=true;
// function 2
}
}
And
var first=true;
function toggle() {
if(first) {
// function 1
}
else {
// function 2
}
first = !first;
}
And
var first=true;
function toggle() {
(first) ? function_1() : function_2();
first != first;
}
function function_1(){}
function function_2(){}
return an new function
var foo = (function(){
var condition
, body
body = function () {
if(condition){
//thing here
} else {
//other things here
}
}
return body
}())`
Best really depends on the criteria your application demands. This might not be the best way to this is certainly a cute way to do it:
function toggler(a, b) {
var current;
return function() {
current = current === a ? b : a;
current();
}
}
var myToggle = toggler(function_1, function_2);
myToggle(); // executes function_1
myToggle(); // executes function_2
myToggle(); // executes function_1
It's an old question but i'd like to contribute too..
Sometimes in large project i have allot of toggle scripts and use global variables to determine if it is toggled or not. So those variables needs to garbage collect for organizing variables, like if i maybe use the same variable name somehow or things like that
You could try something like this..: (using your first example)
function toggle() {
var self = arguments.callee;
if (self.first === true) {
self.first = false;
// function 1
}
else {
self.first = true;
// function 2
}
}
Without a global variable. I just added the property first to the function scope.
This way can be used the same property name for other toggle functions too.
Warning: arguments.callee is forbidden in 'strict mode'
Otherwise you may directly assign the first property to the function using directly the function name
function toggle() {
if (toggle.first === true) {
toggle.first = false;
// function 1
}
else {
toggle.first = true;
// function 2
}
}
I have a function which accepts a string and outputs it one character at a time with a delay. The event occurs when the user clicks a link or button. The problem is that if the user clicks a link and then another before the first one is done, they both run at the same time and output to the screen. It becomes jumbled up.
ex:
string1 : "i like pie very much"
string1 : "so does the next guy"
output : i sloi kdeo epse .... and so on.
Anyone know a method to fix this?
I think I need a way to check if the function is being processed already, then wait till it is done before starting the next.
Place both functions inside an object (because globals are bad), add a variable to the object which knows if a function is executing, and check the variable, like this:
var ns = {
isExecuting:false,
func1: function(){
if (this.isExecuting) { return; }
this.isExecuting = true;
//do stuff 1
this.isExecuting = false;
},
func2: function(){
if (this.isExecuting) { return; }
this.isExecuting = true;
//do stuff 2
this.isExecuting = false;
}
}
and for extra elegance:
var ns = {
isExecuting:false,
executeConditionally:function(action){
if (this.isExecuting) { return; }
this.isExecuting = true;
action();
this.isExecuting = false;
}
func1: function(){
this.executeConditionally(function(){
//stuff
})
},
func2: function(){
this.executeConditionally(function(){
//stuff
})
}
}
add a variable globally or in scope outside the method called IsProcessing and set it to true the first time the method is called, on the method you can then just check if (IsProcessing) return false;
All you need to do is set a variable that indicates whether the function is running:
var isRunning = false;
$('a').click(function({
if(isRunning == false){
isRunning = true;
///Do stuff
isRunning = false;
}
else{
return false;
}
});
Don't you want all the clicks to be taken into account, but in order ?
If so, I suggest you separate streams between adding a click to process, and consuming clicks
:
the html :
<a class="example" href="javascript:void(0)" onclick="delayPushLine();">i like pie very much</a><br/>
<a class="example" href="javascript:void(0)" onclick="delayPushLine();">so does the next guy</a>
<div class="writeThere"></div>
and the javascript (using jQuery a bit)
var charDisplayDelay = 50; // the time between each char display
var displayDelay = 2000; // the time before a click is handled
var lines = [];
var lineIdx = 0, pos = 0;
function delayPushLine(e) {
if (!e) {
e = window.event
}
setTimeout(function() { lines.push(e.srcElement.innerText); }, displayDelay);
}
function showLines () {
if (lines.length > lineIdx) {
if (pos < lines[lineIdx].length) {
$(".writeThere").append(lines[lineIdx].substr(pos,1));
pos++;
} else {
pos = 0;
lineIdx++;
$(".writeThere").append("<br/>");
}
}
}
setInterval("showLines()", charDisplayDelay);
http://jsfiddle.net/kD4JL/1/