Using setTimeout() within a loop

set = [500,1000,1500,2000];
for (var j = 0; j < 4; j++) {
    setTimeout(console.log('Hi'), set[j]);}

What could be causing this code not to display 'Hi' after the specified intervals in the list?

Answer №1

Here is the correct approach:

arr = [500,1000,1500,2000];
for (var index = 0; index < 4; index++) {
    setTimeout(function(){console.log('Greetings')}, arr[index]);
}

This method is preferred because setTimeout requires a callback function instead of a direct statement.

Answer №2

The console.log() function is being called immediately and its return value is passed as an argument to the setTimeout function.

Instead of passing a return value, it is recommended to pass a function. You can achieve this by using the bind() method which will create a new function that invokes log with the appropriate context and specified arguments.

setTimeout(console.log.bind(console, 'Hello'), numberList[index]);

Answer №3

Check out this code snippet

arr = [10, 20, 30, 40];
for (var j = 0; j <= arr.length; j++) {
    (function(ind) {
        setTimeout(function() { console.log(ind); }, j * arr[j]);
    })(j);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Engage with a specific element within the Document Object Model even in the absence of a 'ref' attribute

Is there a better way to set focus on a button within a React component without using ref? The button is part of a third-party library and not immediately available upon componentDidMount. Currently, I am using setTimeout and querySelector which feels like ...

Tips on disabling the default hover effect in NavigationMenuTrigger using vue.js?

I'm a beginner with vue.js and currently working with the <NavigationMenuTrigger/> component from 'radix-vue' Essentially, this component triggers the menu to open when hovered over, and closes it when hovered outside. My goal is to ...

Leveraging retrieved API data to generate numerous components

Hey there! I'm new to JavaScript and I'm working on creating a todo list with fake ToDos from jsonplaceholder using Fetch. My goal is to fetch five different ToDos and display them in separate list items within my list. However, I'm encounte ...

Deactivating form elements using jQuery

I am attempting to utilize jQuery in order to disable a form element once a checkbox is clicked, but for some reason it's not working properly. Can someone help me identify the issue? $('name="globallyAddTime"').click(function() { if ($ ...

How can I retrieve the $index value of an ng-repeat element within a uib-dropdown?

I am currently working on implementing an ng-repeat loop that includes a dropdown menu for each element. I want the dropdown menu to contain functions that operate on the specific element, requiring access to the index of that element. Below is the code sn ...

Utilize JavaScript to save user-selected CSS styles by setting a cookie in jQuery

I am currently using a jQuery styleswitcher to change the stylesheet upon click. Despite trying various solutions, I have been unable to find a resolution to this issue. Could someone please assist me in setting a cookie for this functionality? Markup: ...

Is it possible to incorporate an expression within NG-MODEL?

Is there a way to bind an expression inside the NG-MODEL directive without causing an error? Can this be achieved using a compile function? Below is my HTML markup: <!DOCTYPE html> <html> <head> <title></title> <l ...

Personalized tooltip for React ChartJs

I am currently facing an issue with creating a custom tooltip using the react-chartjs-2 library. Whenever I hover over the chart and change the state of the tooltip's future data, my chart rerenders. At the moment, there is no tooltip present; I am on ...

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

Converting XML to JSON using UTF-8 Encoding

I am currently working with xml2js to convert an XML feed into JSON format. However, I'm facing an issue where certain characters like Æ, Ø & Å are displayed as expected in the XML but appear differently after parsing. After parsing, I receive ...

Enhance numbers with properties in ES2015 strict mode

Is there a way to achieve the following scenario? console.log(a, typeof a); // prints "3 'number'" console.log(typeof a.mymethod()); // prints 'foobar' In non-strict mode this can be done (at least in Node), but strict mode in ECMASc ...

Creating dynamic select boxes in Django Admin using jQuery

In my Contract class, the contract_mod field is designed to extend a contract from a previous one and should only display contracts related to the selected person. The Contract class returns the person field, but since I have no experience with AJAX/jQuery ...

Capturing the row selected within a table using AngularJS

Displayed below is an HTML Code that includes a table which retrieves items from costList and presents them in separate rows. The objective is to exhibit the item value when a row is clicked. How can this be achieved using Angular? Your help is greatly a ...

Discovering pairs of numbers that are not next to each other in an array that has not been

When working with an array of unsorted numbers, the goal is to identify and extract pairs of elements that are not consecutive. Input [2,3,4,5,9,8,10,13] Desired output (2,5)(8,10)(13,13) To achieve this: Input = [2,3,4,5,9,8,10,13] If we arrange the num ...

Having trouble implementing min and max date validation in Angular UI-Bootstrap datepicker with UI-Bootstrap version 1.3.3

My goal is to implement validation in my datepicker, preventing the user from selecting a date within 30 days before or after the current date. Here's the code snippet I'm currently using for the datepicker: <div class="form-group" ng-class=" ...

What is causing the ReferenceError message stating that db is not defined to appear in my code

I am facing an issue with connecting axios to the DB. It is a MYSQL server, and although I can retrieve data using app.get in the server file, the connection does not persist when using express DB connection. Strangely, everything works fine in postman and ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

Is there a way to manipulate the appearance of a scroller using JavaScript?

I'm intrigued by how fellow front-end developers are able to customize the scrollbar shape on a webpage to enhance its appearance. Can anyone guide me on using JavaScript to accomplish this? ...

Exploring the functions of `map` and `filter` in the world of

Consider this input: var m = [{ name: 'foo', routes: [{verb: 'post', path: '/foo1'}, {verb: 'get', path: '/foo2'}] }, { name: 'bar', routes: [{verb: 'put', path: ...