RD2411
RD2411

Reputation: 69

How to iterate over a jquery loop slowly, and replace placeholder text each time

I've tried a few different things such as setting a timeout and calling a function every few seconds, but I can seem to get the following to work:

var searchText = ["1", "2", "3", "4", "5"];


    for(x = 0; x < searchText.length; x++){

        // set the placeholder text
        jQuery('.banner .search-field').attr('placeholder', searchText[x]);



    }

The above iterates over the values in the array but too quickly for the user to see. I can see it's working correctly by checking console.log

I've tried using the delay function but can't get it to work. Is there any way to get this to delay between the updates?

Upvotes: 1

Views: 604

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

You can do it with with a simple for loop and setTimeout,

var secs = 5;
var elem = jQuery('.banner .search-field');
for(x = 1; x <= secs; x++) {
  setTimeout(function(x) {
    elem.attr('placeholder', x);
  }, x * 1000, x);
}

DEMO

Upvotes: 1

Related Questions