How to send discord messages after waiting 1 second - javascript
if (msg.content.toLowerCase() === "!start") {
var gov = setInterval(go, 1000);
var onev = setInterval(one, 1000);
var twov = setInterval(two, 1000);
function two(msg) {
msg.channel.send("https://i.imgur.com/JZOCg5l.png ");
}
function one(msg) {
msg.channel.send("https://i.imgur.com/gTK3Vhn.png ");
}
function go(msg) {
msg.channel.send("https://i.imgur.com/3iVfYIR.png ");
}
function two(msg) { }
function one(msg) { }
function go(msg) { }
msg.channel.sendFile("https://i.imgur.com/kOoyoZQ.png ").then(onev).then(twov).then(gov);
}
This is a very annoying task. I need to send these images about one second appart.
The current framework keeps giving me the following error:
C:\Users\maver\Documents\TestBot\testlev.js:197
msg.channel.sendFile("https://i.imgur.com/3iVfYIR.png ");
^
TypeError: Cannot read property 'channel' of undefined at Timeout.three [as _onTimeout]
(C:\Users\maver\Documents\TestBot\testlev.js:197:17)
at ontimeout (timers.js:478:11)
at tryOnTimeout (timers.js:302:5)
at Timer.listOnTimeout (timers.js:262:5)
I've tried this a multitude of different ways and am just about ready to throw in the towel.
Your syntax is slightly off. When you do function two(msg){... you are actually telling the function that you are going to pass it a new variable and that you want that variable called msg. Because of that, msg (in the context of your function) is undefined. You would have to pass in msg when you call the function from setInterval().
There are 2 ways you can bind msg to your function. The way that I personally like is this:
//...
var gov = setInterval(go.bind(null, msg), 1000);
var onev = setInterval(one.bind(null, msg), 1000);
var twov = setInterval(two.bind(null, msg), 1000);
//...
The .bind() function assigns the value of arguments. With the first argument of the function being called being the second argument of bind(). The first argument of bind() is what should be used as the value of this inside the function.
The other way to do this is with an anonymous function
//...
var gov = setInterval(function(){go(msg)}, 1000);
var onev = setInterval(function(){one(msg)}, 1000);
var twov = setInterval(function(){two(msg)}, 1000);
//...
Also note, setInterval() repeats a function call ever period. You may be looking for setTimeout() which would only fire the functions once after a delay.
When you use setInterval, you should know it will call the function, but will not provide any parameters to it (or even this). One way to fix it would be by using bind:
setInterval(go.bind(null, msg), 1000)
This would work, because bind() will create a new function where the parameters are "magically set in advance".
Another option in this case would be to simply not re-declare msg in the three functions - in that case, javascript will try to find msg from the outer scope, where it exists:
function two() {
msg.channel.send("https://i.imgur.com/JZOCg5l.png ");
}
Third, you shouldn't be using setInterval, but setTimeout, which will only call the function once.
The fourth problem you have is with timing. First, all three setTimeout calls happen at the same time, so all three functions will be called in one second (after 1000 millis). An easy fix would be simply:
setTimeout(go, 1000);
setTimeout(one, 2000);
setTimeout(two, 3000);
However, that will completely ignore how long it takes to send each message (which may or may not be what you want). If you wanted to wait a second after the previous message is sent, then you'd have to do something like:
msg.channel.sendFile("https://i.imgur.com/kOoyoZQ.png ").then(function() {
setTimeout(go, 1000);
});
function go() {
msg.channel.send("https://i.imgur.com/3iVfYIR.png").then(function() {
setTimeout(one, 1000);
});
}
// etc
That would be very tedious, as all the functions will look very similar. So a better approach would be to create a list of messages, then have a single function to send all of them:
var msgs = [
"https://i.imgur.com/kOoyoZQ.png",
"https://i.imgur.com/JZOCg5l.png",
"https://i.imgur.com/gTK3Vhn.png",
"https://i.imgur.com/3iVfYIR.png"
];
function sendMsgs(msgs, delay) {
if (msgs.length < 1) return; // we're done
var remain = msgs.slice(1);
var sendRemain = sendMsgs.bind(null, remain, delay);
msg.channel.send(msgs[0]).then(function() {
setTimeout(sendRemain, delay);
});
}
sendMsgs(msgs, 1000);
Your code is executed immediately because you have to maintain the value anf promises you are using is not correctly used.
You can do it as follows :
if (msg.content.toLowerCase() === "!start") {
var urls = ["https://i.imgur.com/kOoyoZQ.png",
"https://i.imgur.com/JZOCg5l.png",
"https://i.imgur.com/gTK3Vhn.png",
"https://i.imgur.com/3iVfYIR.png" ];
function gov(urls){
for(let k=0; k<urls.length;k++){
setTimeout(function() { msg.channel.send(k); },k*1000)
}
}
gov(urls);
}
Related
How to resolve a promise with a parameter in setTimeout [duplicate]
I have some JavaScript code that looks like: function statechangedPostQuestion() { //alert("statechangedPostQuestion"); if (xmlhttp.readyState==4) { var topicId = xmlhttp.responseText; setTimeout("postinsql(topicId)",4000); } } function postinsql(topicId) { //alert(topicId); } I get an error that topicId is not defined Everything was working before I used the setTimeout() function. I want my postinsql(topicId) function to be called after some time. What should I do?
setTimeout(function() { postinsql(topicId); }, 4000) You need to feed an anonymous function as a parameter instead of a string, the latter method shouldn't even work per the ECMAScript specification but browsers are just lenient. This is the proper solution, don't ever rely on passing a string as a 'function' when using setTimeout() or setInterval(), it's slower because it has to be evaluated and it just isn't right. UPDATE: As Hobblin said in his comments to the question, now you can pass arguments to the function inside setTimeout using Function.prototype.bind(). Example: setTimeout(postinsql.bind(null, topicId), 4000);
In modern browsers (ie IE11 and beyond), the "setTimeout" receives a third parameter that is sent as parameter to the internal function at the end of the timer. Example: var hello = "Hello World"; setTimeout(alert, 1000, hello); More details: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout http://arguments.callee.info/2008/11/10/passing-arguments-to-settimeout-and-setinterval/
After doing some research and testing, the only correct implementation is: setTimeout(yourFunctionReference, 4000, param1, param2, paramN); setTimeout will pass all extra parameters to your function so they can be processed there. The anonymous function can work for very basic stuff, but within instance of a object where you have to use "this", there is no way to make it work. Any anonymous function will change "this" to point to window, so you will lose your object reference.
This is a very old question with an already "correct" answer but I thought I'd mention another approach that nobody has mentioned here. This is copied and pasted from the excellent underscore library: _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; You can pass as many arguments as you'd like to the function called by setTimeout and as an added bonus (well, usually a bonus) the value of the arguments passed to your function are frozen when you call setTimeout, so if they change value at some point between when setTimeout() is called and when it times out, well... that's not so hideously frustrating anymore :) Here's a fiddle where you can see what I mean.
I recently came across the unique situation of needing to use a setTimeout in a loop. Understanding this can help you understand how to pass parameters to setTimeout. Method 1 Use forEach and Object.keys, as per Sukima's suggestion: var testObject = { prop1: 'test1', prop2: 'test2', prop3: 'test3' }; Object.keys(testObject).forEach(function(propertyName, i) { setTimeout(function() { console.log(testObject[propertyName]); }, i * 1000); }); I recommend this method. Method 2 Use bind: var i = 0; for (var propertyName in testObject) { setTimeout(function(propertyName) { console.log(testObject[propertyName]); }.bind(this, propertyName), i++ * 1000); } JSFiddle: http://jsfiddle.net/MsBkW/ Method 3 Or if you can't use forEach or bind, use an IIFE: var i = 0; for (var propertyName in testObject) { setTimeout((function(propertyName) { return function() { console.log(testObject[propertyName]); }; })(propertyName), i++ * 1000); } Method 4 But if you don't care about IE < 10, then you could use Fabio's suggestion: var i = 0; for (var propertyName in testObject) { setTimeout(function(propertyName) { console.log(testObject[propertyName]); }, i++ * 1000, propertyName); } Method 5 (ES6) Use a block scoped variable: let i = 0; for (let propertyName in testObject) { setTimeout(() => console.log(testObject[propertyName]), i++ * 1000); } Though I would still recommend using Object.keys with forEach in ES6.
Hobblin already commented this on the question, but it should be an answer really! Using Function.prototype.bind() is the cleanest and most flexible way to do this (with the added bonus of being able to set the this context): setTimeout(postinsql.bind(null, topicId), 4000); For more information see these MDN links: https://developer.mozilla.org/en/docs/DOM/window.setTimeout#highlighter_547041 https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Function/bind#With_setTimeout
You can pass the parameter to the setTimeout callback function as: setTimeout(function, milliseconds, param1, param2, ...) eg. function myFunction() { setTimeout(alertMsg, 3000, "Hello"); } function alertMsg(message) { alert(message) }
Some answers are correct but convoluted. I am answering this again, 4 years later, because I still run into overly complex code to solve exactly this question. There IS an elegant solution. First of all, do not pass in a string as the first parameter when calling setTimeout because it effectively invokes a call to the slow "eval" function. So how do we pass in a parameter to a timeout function? By using closure: settopic=function(topicid){ setTimeout(function(){ //thanks to closure, topicid is visible here postinsql(topicid); },4000); } ... if (xhr.readyState==4){ settopic(xhr.responseText); } Some have suggested using anonymous function when calling the timeout function: if (xhr.readyState==4){ setTimeout(function(){ settopic(xhr.responseText); },4000); } The syntax works out. But by the time settopic is called, i.e. 4 seconds later, the XHR object may not be the same. Therefore it's important to pre-bind the variables.
I know its been 10 yrs since this question was asked, but still, if you have scrolled till here, i assume you're still facing some issue. The solution by Meder Omuraliev is the simplest one and may help most of us but for those who don't want to have any binding, here it is: Use Param for setTimeout setTimeout(function(p){ //p == param1 },3000,param1); Use Immediately Invoked Function Expression(IIFE) let param1 = 'demon'; setTimeout(function(p){ // p == 'demon' },2000,(function(){ return param1; })() ); Solution to the question function statechangedPostQuestion() { //alert("statechangedPostQuestion"); if (xmlhttp.readyState==4) { setTimeout(postinsql,4000,(function(){ return xmlhttp.responseText; })()); } } function postinsql(topicId) { //alert(topicId); }
Replace setTimeout("postinsql(topicId)", 4000); with setTimeout("postinsql(" + topicId + ")", 4000); or better still, replace the string expression with an anonymous function setTimeout(function () { postinsql(topicId); }, 4000); EDIT: Brownstone's comment is incorrect, this will work as intended, as demonstrated by running this in the Firebug console (function() { function postinsql(id) { console.log(id); } var topicId = 3 window.setTimeout("postinsql(" + topicId + ")",4000); // outputs 3 after 4 seconds })(); Note that I'm in agreeance with others that you should avoid passing a string to setTimeout as this will call eval() on the string and instead pass a function.
My answer: setTimeout((function(topicId) { return function() { postinsql(topicId); }; })(topicId), 4000); Explanation: The anonymous function created returns another anonymous function. This function has access to the originally passed topicId, so it will not make an error. The first anonymous function is immediately called, passing in topicId, so the registered function with a delay has access to topicId at the time of calling, through closures. OR This basically converts to: setTimeout(function() { postinsql(topicId); // topicId inside higher scope (passed to returning function) }, 4000); EDIT: I saw the same answer, so look at his. But I didn't steal his answer! I just forgot to look. Read the explanation and see if it helps to understand the code.
The easiest cross browser solution for supporting parameters in setTimeout: setTimeout(function() { postinsql(topicId); }, 4000) If you don't mind not supporting IE 9 and lower: setTimeout(postinsql, 4000, topicId); https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
I know it's old but I wanted to add my (preferred) flavour to this. I think a pretty readable way to achieve this is to pass the topicId to a function, which in turn uses the argument to reference the topic ID internally. This value won't change even if topicId in the outside will be changed shortly after. var topicId = xmlhttp.responseText; var fDelayed = function(tid) { return function() { postinsql(tid); }; } setTimeout(fDelayed(topicId),4000); or short: var topicId = xmlhttp.responseText; setTimeout(function(tid) { return function() { postinsql(tid); }; }(topicId), 4000);
The answer by David Meister seems to take care of parameters that may change immediately after the call to setTimeout() but before the anonymous function is called. But it's too cumbersome and not very obvious. I discovered an elegant way of doing pretty much the same thing using IIFE (immediately inviked function expression). In the example below, the currentList variable is passed to the IIFE, which saves it in its closure, until the delayed function is invoked. Even if the variable currentList changes immediately after the code shown, the setInterval() will do the right thing. Without this IIFE technique, the setTimeout() function will definitely get called for each h2 element in the DOM, but all those calls will see only the text value of the last h2 element. <script> // Wait for the document to load. $(document).ready(function() { $("h2").each(function (index) { currentList = $(this).text(); (function (param1, param2) { setTimeout(function() { $("span").text(param1 + ' : ' + param2 ); }, param1 * 1000); })(index, currentList); }); </script>
In general, if you need to pass a function as a callback with specific parameters, you can use higher order functions. This is pretty elegant with ES6: const someFunction = (params) => () => { //do whatever }; setTimeout(someFunction(params), 1000); Or if someFunction is first order: setTimeout(() => someFunction(params), 1000);
Note that the reason topicId was "not defined" per the error message is that it existed as a local variable when the setTimeout was executed, but not when the delayed call to postinsql happened. Variable lifetime is especially important to pay attention to, especially when trying something like passing "this" as an object reference. I heard that you can pass topicId as a third parameter to the setTimeout function. Not much detail is given but I got enough information to get it to work, and it's successful in Safari. I don't know what they mean about the "millisecond error" though. Check it out here: http://www.howtocreate.co.uk/tutorials/javascript/timers
How i resolved this stage ? just like that : setTimeout((function(_deepFunction ,_deepData){ var _deepResultFunction = function _deepResultFunction(){ _deepFunction(_deepData); }; return _deepResultFunction; })(fromOuterFunction, fromOuterData ) , 1000 ); setTimeout wait a reference to a function, so i created it in a closure, which interprete my data and return a function with a good instance of my data ! Maybe you can improve this part : _deepFunction(_deepData); // change to something like : _deepFunction.apply(contextFromParams , args); I tested it on chrome, firefox and IE and it execute well, i don't know about performance but i needed it to be working. a sample test : myDelay_function = function(fn , params , ctxt , _time){ setTimeout((function(_deepFunction ,_deepData, _deepCtxt){ var _deepResultFunction = function _deepResultFunction(){ //_deepFunction(_deepData); _deepFunction.call( _deepCtxt , _deepData); }; return _deepResultFunction; })(fn , params , ctxt) , _time) }; // the function to be used : myFunc = function(param){ console.log(param + this.name) } // note that we call this.name // a context object : myObjet = { id : "myId" , name : "myName" } // setting a parmeter myParamter = "I am the outer parameter : "; //and now let's make the call : myDelay_function(myFunc , myParamter , myObjet , 1000) // this will produce this result on the console line : // I am the outer parameter : myName Maybe you can change the signature to make it more complient : myNass_setTimeOut = function (fn , _time , params , ctxt ){ return setTimeout((function(_deepFunction ,_deepData, _deepCtxt){ var _deepResultFunction = function _deepResultFunction(){ //_deepFunction(_deepData); _deepFunction.apply( _deepCtxt , _deepData); }; return _deepResultFunction; })(fn , params , ctxt) , _time) }; // and try again : for(var i=0; i<10; i++){ myNass_setTimeOut(console.log ,1000 , [i] , console) } And finaly to answer the original question : myNass_setTimeOut( postinsql, 4000, topicId ); Hope it can help ! ps : sorry but english it's not my mother tongue !
this works in all browsers (IE is an oddball) setTimeout( (function(x) { return function() { postinsql(x); }; })(topicId) , 4000);
if you want to pass variable as param lets try this if requirement is function and var as parmas then try this setTimeout((param1,param2) => { alert(param1 + param2); postinsql(topicId); },2000,'msg1', 'msg2') if requirement is only variables as a params then try this setTimeout((param1,param2) => { alert(param1 + param2) },2000,'msg1', 'msg2') You can try this with ES5 and ES6
setTimeout is part of the DOM defined by WHAT WG. https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html The method you want is:— handle = self.setTimeout( handler [, timeout [, arguments... ] ] ) Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler. setTimeout(postinsql, 4000, topicId); Apparently, extra arguments are supported in IE10. Alternatively, you can use setTimeout(postinsql.bind(null, topicId), 4000);, however passing extra arguments is simpler, and that's preferable. Historical factoid: In days of VBScript, in JScript, setTimeout's third parameter was the language, as a string, defaulting to "JScript" but with the option to use "VBScript". https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa741500(v%3Dvs.85)
You can try default functionality of 'apply()' something like this, you can pass more number of arguments as your requirement in the array function postinsql(topicId) { //alert(topicId); } setTimeout( postinsql.apply(window,["mytopic"]) ,500);
//Some function, with some arguments, that need to run with arguments var a = function a(b, c, d, e){console.log(b, c, d, e);} //Another function, where setTimeout using for function "a", this have the same arguments var f = function f(b, c, d, e){ setTimeout(a.apply(this, arguments), 100);} f(1,2,3,4); //run //Another function, where setTimeout using for function "a", but some another arguments using, in different order var g = function g(b, c, d, e){ setTimeout(function(d, c, b){a.apply(this, arguments);}, 100, d, c, b);} g(1,2,3,4);
#Jiri Vetyska thanks for the post, but there is something wrong in your example. I needed to pass the target which is hovered out (this) to a timed out function and I tried your approach. Tested in IE9 - does not work. I also made some research and it appears that as pointed here the third parameter is the script language being used. No mention about additional parameters. So, I followed #meder's answer and solved my issue with this code: $('.targetItemClass').hover(ItemHoverIn, ItemHoverOut); function ItemHoverIn() { //some code here } function ItemHoverOut() { var THIS = this; setTimeout( function () { ItemHoverOut_timeout(THIS); }, 100 ); } function ItemHoverOut_timeout(target) { //do something with target which is hovered out } Hope, this is usefull for someone else.
As there is a problem with the third optonal parameter in IE and using closures prevents us from changing the variables (in a loop for example) and still achieving the desired result, I suggest the following solution. We can try using recursion like this: var i = 0; var hellos = ["Hello World1!", "Hello World2!", "Hello World3!", "Hello World4!", "Hello World5!"]; if(hellos.length > 0) timeout(); function timeout() { document.write('<p>' + hellos[i] + '<p>'); i++; if (i < hellos.length) setTimeout(timeout, 500); } We need to make sure that nothing else changes these variables and that we write a proper recursion condition to avoid infinite recursion.
// These are three very simple and concise answers: function fun() { console.log(this.prop1, this.prop2, this.prop3); } let obj = { prop1: 'one', prop2: 'two', prop3: 'three' }; let bound = fun.bind(obj); setTimeout(bound, 3000); // or function funOut(par1, par2, par3) { return function() { console.log(par1, par2, par3); } }; setTimeout(funOut('one', 'two', 'three'), 5000); // or let funny = function(a, b, c) { console.log(a, b, c); }; setTimeout(funny, 2000, 'hello', 'worldly', 'people');
// These are three very simple and concise answers: function fun() { console.log(this.prop1, this.prop2, this.prop3); } let obj = { prop1: 'one', prop2: 'two', prop3: 'three' }; let bound = fun.bind(obj); setTimeout(bound, 3000); // or function funOut(par1, par2, par3) { return function() { console.log(par1, par2, par3); } }; setTimeout(funOut('one', 'two', 'three'), 5000); // or let funny = function(a, b, c) { console.log(a, b, c); }; setTimeout(funny, 2000, 'hello', 'worldly', 'people');
I think you want: setTimeout("postinsql(" + topicId + ")", 4000);
You have to remove quotes from your setTimeOut function call like this: setTimeout(postinsql(topicId),4000);
Answering the question but by a simple addition function with 2 arguments. var x = 3, y = 4; setTimeout(function(arg1, arg2) { return () => delayedSum(arg1, arg2); }(x, y), 1000); function delayedSum(param1, param2) { alert(param1 + param2); // 7 }
Implement debounce: how to make three invocations result in one effective call?
How can I invoke three times a function with a setTimeOut but just print it once after 100 milliseconds?? This is the definition of debounce that I have to implement: Debounce ignores the calls made to it during the timer is running and when the timer expires it calls the function with the last function call arguments, so I want to achieve that with Javascript A function will be debounced as follows: receivedEvent = debounce(receivedEvent, 100) My attempt: function debounce(func, timeInterval) { return (args) => { setTimeout(func, timeInterval) } } function receivedEvent() { console.log('receive') } receivedEvent(); receivedEvent(); receivedEvent(); But this still generates 3 outputs. I need it to only produce one output according to the requirements.
In your attempt you did not call debounce, but just called your own function receivedEvent. Maybe the site where your attempt is tested will do this for you, but we cannot know this from your question. Just make sure it is called. To test the requirements you need to use a better use case: one based on a function that receives arguments. This is needed because you must prove that the debounced function is called after the timeout with the last passed arguments. The key to this pattern is to use variables within a closure: function debounce(func, timeInterval) { let timer; let lastArgs; return (...args) => { lastArgs = args; // update so we remember last used args if (timer) return; // not ready yet to call function... timer = setTimeout(() => { func(...lastArgs); timer = 0; // reset timer (to allow more calls...) }, timeInterval); } } function receivedEvent(arg) { console.log('receive ' + arg) } receivedEvent = debounce(receivedEvent, 100) receivedEvent("a"); receivedEvent("b"); receivedEvent("c"); // Output will be "c" after 100ms Note that the question's definition of "debounce" deviates a bit from its usual definition, where the first invocation actually calls the function immediately, and only then starts the timeout (cooldown-period).
Javascript : setTimeout use on an anonymous function expression
I recently started learning javascript to help maintain some stuff and ran into this issue today: this.moveChar = function(){ // body here setTimeout(moveChar,1000); } this.initialise= function(){ this.moveChar(); } When initialise is called, I expected moveChar to be called, then repeated call itself once every 1000ms However, what actually happens is moveChar gets called once then that's it. Based on other stackoverflow posts I read, I suspected it might be something to do with the function being expressed rather than declared. I have tried to use this.moveChar = function recMove(){ // body here setTimeout(recMove,1000); } without luck either. Any suggestions on how I can fix this? EDIT: Main thing I need to do is have the moveChar function called once every second. If there is a better approach than setTimeout recursion, I'm open to it
this.moveChar is not the same as moveChar, unless this is the global scope object like window. this.moveChar is a property on an object, while moveChar would reference any variable in a visible scope chain. You can change it to a couple of things in order to keep scope of whatever object is being used: Using an arrow function this.moveChar = function(){ // body here setTimeout(()=>this.moveChar(),1000); } Using .bind() this.moveChar = function(){ // body here setTimeout(this.moveChar.bind(this),1000); }
You might want to consider using setInterval() which is the more appropriate API for this task. What setInterval() does is - it will repeatedly call the given function upon a certain interval is reached. See: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval Quote: Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. Returns an intervalID. Example: Assuming moveChar() contains your operation logic. Then to repeat it you'll do this 1 line. let moveChar = function(){ // Do stuff console.log("Hi thanks for calling me!"); } setInterval(moveChar, 1000);
Are you using this in side body here? If so, you should bind correct context while call. this.moveChar = function(){ // body here setTimeout(this.moveChar.bind(this), 1000); } Or use anonymous function: this.moveChar = function(){ // body here var that = this; setTimeout(function(){ that.moveChar(); }, 1000); } Or arrow function: this.moveChar = function(){ // body here setTimeout(() => this.moveChar(), 1000); } Same notes apply to setInterval variant: this.initialise= function(){ setInterval(this.moveChar.bind(this), 1000); // var that = this; // setInterval(function(){that.moveChar();}, 1000); // setInterval(() => this.moveChar(), 1000); }
this.moveChar = function(){ // body here alert('called moveChar'); } this.initialise= function(){ setInterval(function(){moveChar();},1000); } this.initialise();//call here
How to pass arguments to a function in setTimeout
I have the following code: function fn($){ return function(){ innerFn = function(){ setTimeout(show, 1000); }; show = function(){ $.alert("TEST"); } } } But, after one second, when the function show is run, it says $ is undefined. How do I resolve this issue?
how to pass arguments to a function in setTimeout setTimeout has a built in mechanism for adding params var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]); use it. If you're going to use this - you should be careful. but that's another question.
There are a number of things at play here. The most important being that your setTimeout never gets called, since innerFn never gets called. This should do the trick. function fn($){ return function(){ setTimeout(function(){ $.alert("TEST"); }, 1000); } } fn(window)(); //triggers your alert after 1000ms
Your code makes no any sense, because nothing is called: function fn($){ return function(){ innerFn = function(){ setTimeout(show, 1000); }; show = function(){ $.alert("TEST"); } } } Let's say I'm calling fn passing window, then a function is returned, that I can executed. But because this function is containing only function declaration - you also forget var so you pollute the global scope, that is bad - nothing is happen. You'll need at least one function call inside, like: function fn($){ return function(){ var innerFn = function(){ setTimeout(show, 1000); }; var show = function(){ $.alert("TEST"); } innerFn(); } } fn(window)(); And that will works. However, it's definitely redundant. You can just have: function fn($){ return function(){ function show(){ $.alert("TEST"); } setTimeout(show, 1000); } } To obtain the same result. However, if you're goal is just bound an argument to setTimeout, you can use bind. You could use the 3rd parameter of setTimeout as the documentation says, but it seems not supported in IE for legacy reason. So, an example with bind will looks like: function show() { this.alert('test'); } setTimeout(show.bind(window), 1000); Notice also that window is the global object by default, so usually you do not have to do that, just alert is enough. However, I suppose this is not your actual code, but just a mere test, as the alert's string says. If you prefer having window as first parameter instead, and you're not interested in the context object this, you can do something like: function show($) { $.alert('test'); } setTimeout(show.bind(null, window), 1000);
how to write a recursive method in JavaScript using window.setTimeout()?
I'm writing a JavaSCript class that has a method that recursively calls itself. Scheduler.prototype.updateTimer = function () { document.write( this._currentTime ); this._currentTime -= 1000; // recursively calls itself this._updateUITimerHandler = window.setTimeout( arguments.callee , 1000 ); } Property description: _currentTime: the currentTime of the timer in miliseconds. _updateUITimerHandler: stores the reference so can be used later with clearTimeout(). my problem is where I'm using recursion with setTimeout(). I know setTimeout() will accept some string to execute, or a reference to a function. since this function is method of an object, I don't know how to call it from outside. so I used the second format of setTimeout() and passed in a reference to the method itself. but it does not work.
Try this:- Scheduler.prototype.startTimer = function() { var self = this; function updateTimer() { this._currentTime -= 1000; self.hTimer = window.setTimeout(updateTimer, 1000) self.tick() } this.hTimer = window.setTimeout(updateTimer, 1000) } Scheduler.prototype.stopTimer = function() { if (this.hTimer != null) window.clearTimeout(this.hTimer) this.hTimer = null; } Scheduler.prototype.tick = function() { //Do stuff on timer update }
Well the first thing to say is that if you're calling setTimeout but not changing the interval, you should be using setInterval. edit (update from comment): you can keep a reference from the closure if used as a class and setInterval/clearInterval don't require re-referencing. edit2: it's been pointed out that you wrote callee which will work quite correctly and 100% unambiguously. Out of completeness, this works: function f() { alert('foo'); window.setTimeout(arguments.callee,5000); } f(); so I tried out document.write instead of alert and that is what appears to be the problem. doc.write is fraught with problems like this because of opening and closing the DOM for writing, so perhaps what you needed is to change the innerHTML of your target rather than doc.write
You could hold a pointer towards it... /* ... */ var func = arguments.callee; this._updateUITimerHandler = window.setTimeout(function() { func(); }, 1000); /* ... */