setTimeout global variable [duplicate] - settimeout

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
var delayTime = 2000;
for(var i = 0; i<this.textToWrite.length; i++){
setTimeout(
(
function (s){
return function () {
this.writeText += s;
console.log(this.writeText);
}
}(this.textToWrite[i])
), delayTime)
delayTime += 2000;
}
have some problem with this.writeText. It's global variable but when i even comment += s line then i have undefined value... (I set writeText: string = "" globaly) Is this.writeText reference to global variable? How can I access global variables in this example?
I need assing char from textToWrite object to writeText with 2s delay.

The problem can be that you used function word.
setTimeout(
((s) => {
return () => {
this.writeText += s;
console.log(this.writeText);
}
}(this.textToWrite[i])
), delayTime)
Another way is to use it without this if its global variable:
setTimeout(
((s) => {
return () => {
writeText += s;
console.log(this.writeText);
}
}(this.textToWrite[i])
), delayTime)

Only use arrow functions
settimeout(x => {
console.log(x);
}, 1000);
not like this and it will not accept out side parameters
settimeout(funtion(x) {
console.log(x);
}, 1000);

Related

Unable to Understand this Flutter Closure Function Code?

var callbacks = [];
for (var i = 0; i < 2; i++) {
callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());
I dont Understand Two Things :
print(i) is of return-type Void, shouldnt the compiler show "error", because the work of print(i) is to print the item to the console and not return something.
in the line " callbacks.forEach((c) => c()); " how come c() became a function, because it was a parameter inside the lambda function to get values.
the link of the Code :
https://dart.dev/guides/language/language-tour#type-test-operators
under for Loops
PS : I am a beginner to this syntax, so Thank you so much for your Help Guys !
var callbacks = [];
for (var i = 0; i < 2; i++) {
callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());
Here, () => print(i) is a closure which takes no arguments and returns void. In the loop, you add these functions to the callback list.
(c) => c() is a closure which takes a dynamic parameter and attempts to call it (i.e. calls c.call()).
Some type safety might be helpful here, for example:
final callbacks = <void Function()>[]; // an empty list of functions that look like () -> void
for (var i = 0; i < 2; i++) {
final void Function() callback = () => print(i);
callbacks.add(callback);
}
callbacks.forEach((void Function() callback) => callback());
In this example, because callbacks has a type of List<void Function()>, the parameter of the function passed to forEach is a void Function(), which means you can call it with c()

why writing function of setTimeout separately would not work

I am trying to build 'Simon Game' and used setTimeout method to lighten the buttons. when I write the the functions directly inside the setTimeout method it works.
$(function(){
var randPattern=[];
var buttonId=['red','yellow','green','blue'];
var origColor=['#B40404','#D7DF01','#0B610B','#0B0B61'];
var patternColor=['#F78181','#F4FA58','#A9BCF5','#81F781'];
var level= 5;
var count= 0;
var time= 1000;
$('#start').click(function gameStart() {
patternGenerate();
for(i=0; i<randPattern.length; i++){
display(i);
}
});
function patternGenerate() {
for(var h=0; h<level; h++){
randPattern.push( Math.floor( Math.random()*4) );
}
}
function display(i){
setTimeout(function(){document.getElementById(buttonId[randPattern[i]]).style.backgroundColor = patternColor[randPattern[i]];document.getElementById(randPattern[i]).play();}, 1500*i);
setTimeout(function(){document.getElementById(buttonId[randPattern[i]]).style.backgroundColor = origColor[randPattern[i]]}, 750+1500*i );
}
but when I write the functions that is going inside setTimeout method separately, such function a(i), and function b(i). It doesn't work. And the console says ''cannot read the property 'style' of null''. I think there is no difference between these two. I can't understand why the second way doesn't work while the first one does.
$(function(){
var randPattern=[];
var buttonId=['red','yellow','green','blue'];
var origColor=['#B40404','#D7DF01','#0B610B','#0B0B61'];
var patternColor=['#F78181','#F4FA58','#A9BCF5','#81F781'];
var level= 5;
var count= 0;
var time= 1000;
$('#start').click(function gameStart() {
patternGenerate();
for(i=0; i<randPattern.length; i++){
display(i);
}
});
function patternGenerate() {
for(var h=0; h<level; h++){
randPattern.push( Math.floor( Math.random()*4) );
}
}
function a (i){
document.getElementById(buttonId[randPattern[i]]).style.backgroundColor = patternColor[randPattern[i]];
document.getElementById(randPattern[i]).play();
}
function b (i){
document.getElementById(buttonId[randPattern[i]]).style.backgroundColor = origColor[randPattern[i]];
}
function display(i){
setTimeout(a,1500*i);
setTimeout(b,750+1500*i);
}
});
a and b expect to be passed an argument which will be assigned to i.
While you have a variable called i in the display function: You aren't passing it to a or b.
function display(i){
setTimeout( a, 1500*i, i );
setTimeout( b, 750+1500*i, i );
}
You are using an i inside function display(i){ but this variable is not passed to a or b. If you want to pass a variable, you still need to create a new closure and call your function from it:
function display(i){
setTimeout(function() { a(i) }, 1500*i);
setTimeout(function() { b(i) }, 750+1500*i);
}

TYpescript : Static methods on Function as class

I have a fn that inherit an existing fn ( take Angular1 $q for example )
//$q original behavior
var defer = $q.defer();
defer.promise.then(function(result){})
//or
$q( (resolve, reject) => {
//promise execution here
}).then(function(result){});
If I want to decorate it, I would do :
var Qdecorator = function($delegate) {
var Q = function(resolver:any): any {
//do some extra stuff here
return $delegate.apply($delegate, arguments);
}
//Assign the static methods here:
Q.defer = function() {
//do some stuff
return $delegate.defer.apply($delegate, []);
}
//same goes for race, when, resole reject and so on
return Q;
}
Problem is that typescript complains about
Property defer, race, when, resolve, etc... does not exist on type '(resolver: any) => any'
I tried to use the IQService, and IPromise with no luck, btu I'd like to raise a more global question :
How do I define late static methods on function() that return an object without using new
I am copying pasting the answer to my question from this link:
https://www.typescriptlang.org/docs/handbook/interfaces.html
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

How to pass a test if expect fails

I have this code
it('This should pass anyway', function (done) {
testObj.testIt(regStr);
});
testObj
this.testIt = function (regStr) {
selector.count().then(function (orgCount) {
for (var curr = 0; curr < count; curr++) {
checkField(curr, regStr);
}
});
};
function checkField(curr, regStr) {
selector.get(curr).all(by.tagName('li')).get(0).getInnerHtml().then(function (text) {
expect(text).to.match(regStr, curr + '#ERR');
});
}
If one of these expects get a failure, test fails. How can i handle this? I mean - can i somehow count passed and failed expect()ations and return it? or, at least, dont let test break on first error.
I've tried try-catch, but nothing good happened.
it('This should pass anyway', function (done) {
try {
testObj.testIt(regStr);
} catch (e) {
console.log('#err' + e);
}
});
And then i wanted to use done(), but havent found any examples to do the similar. Can u please help me?
Sry for my english
UPD
You can return either null or a string from checkField(), join them up, and expect the array to be empty:
this.testIt = function (regStr) {
selector.count().then(function (orgCount) {
var errors = [];
for (var curr = 0; curr < orgCount; curr++) {
var e = checkField(curr, regStr);
if (e) { errors.push(e); }
}
assert.equal(0, errors.length, errors);
});
};
A cleaner approach would be to use map() to collect the data into an array:
var data = selector.map(function (elm) {
return elm.element(by.tagName('li')).getText();
});
expect(data).toEqual(["test1", "test2", "test3"]);

How to stop setTimeInterval function manually in smartface?

I create a setInterval method like below, I want to stop it anytime from anywhere. By the way, that function is in a if-else statement, so I cannot access the stop function.
How can it be possible?
var intervalID = setInterval(function () {
if (flag) {
stopTimer();
Pages.Page1.Label1.text = "";
}
if (time == 0) {
stopTimer();
Pages.Page1.Label1.text = "";
Device.makeCall(callNumber.rows[0][0]);
} else
updateTime();
}, 1000);
function updateTime() {
time = time - 1;
Pages.Page1.Label1.text = time;
}
function stopTimer() {
clearInterval(intervalID);
}
Just set the flag variable to true.
flag = true;
Alternatively, i would suggest to declare your functions outside of the if / else scope .
For instance, create a timer instance with start / stop methods as such :
timer = function() {};
timer.prototype.start = function ()
{
this.timerId = setInterval(function () {
/* ... */
/* call to doWork here or simply your code */
}, 1000);
}
timer.prototype.doWork = function ()
{
// override here if you want and wall doWork in setInterval
}
timer.prototype.stop = function ()
{
clearInterval(this.timerId);
}
var t = new timer();
// start the timer
t.start();
// stop the timer
t.stop();
This way you can handle your timer as you want.