What is the JavaScript version of sleep()?

2017 — 2021 update Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice: function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } Or as a one-liner: await new Promise(r => setTimeout(r, 2000)); Or const sleep = ms … Read more

What is the difference between call and apply?

The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is “A for array and C for comma.” See MDN’s documentation on apply and call. Pseudo syntax: theFunction.apply(valueForThis, arrayOfArgs) theFunction.call(valueForThis, arg1, arg2, …) There is also, as of ES6, the … Read more

How do I correctly clone a JavaScript object?

2022 update There’s a new JS standard called structured cloning. It works on all browsers: const clone = structuredClone(object); Old answer To do this for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object’s prototype that should be left in … Read more

Loop through an array in JavaScript

Three main options: for (var i = 0; i < xs.length; i++) { console.log(xs[i]); } xs.forEach((x, i) => console.log(x)); for (const x of xs) { console.log(x); } Detailed examples are below. 1. Sequential for loop: var myStringArray = [“Hello”,”World”]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { console.log(myStringArray[i]); //Do … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)