Recent Entries 4
- principle critical 112d agoTypeScript - use correct version of setTimeout (node vs window)I am working on upgrading some old TypeScript code to use the latest compiler version, and I'm having trouble with a call to `setTimeout`. The code expects to call the browser's `setTimeout` function which returns a number: `setTimeout(handler: (...args: any[]) => void, timeout: number): number;` However, the compiler is resolving this to the node implementation instead, which returns a NodeJS.Timer: ` setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;` This code does not run in node, but the node typings are getting pulled in as a dependency to something else (not sure what). How can I instruct the compiler to pick the version of `setTimeout` that I want? Here is the code in question: ``` let n: number; n = setTimeout(function () { /* snip */ }, 500); ``` This produces the compiler error: TS2322: Type 'Timer' is not assignable to type 'number'.
- snippet critical 112d agoHow can I pass a parameter to a setTimeout() callback?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?
- pattern critical 112d agoReact hooks - right way to clear timeouts and intervalsI don't understand why is when I use `setTimeout` function my react component start to infinite console.log. Everything is working, but PC start to lag as hell. Some people saying that function in timeout changing my state and that rerender component, that sets new timer and so on. Now I need to understand how to clear it's right. ``` export default function Loading() { // if data fetching is slow, after 1 sec i will show some loading animation const [showLoading, setShowLoading] = useState(true) let timer1 = setTimeout(() => setShowLoading(true), 1000) console.log('this message will render every second') return 1 } ``` Clear in different version of code not helping to: ``` const [showLoading, setShowLoading] = useState(true) let timer1 = setTimeout(() => setShowLoading(true), 1000) useEffect( () => { return () => { clearTimeout(timer1) } }, [showLoading] ) ```
- gotcha major pending 121d agoGotcha: JavaScript closures in setTimeout and event handlersVariables in setTimeout callbacks or event handlers have unexpected values due to closure over the variable, not the value.