Blueboye
Blueboye

Reputation: 1494

How to call a function in a delayed manner

I have a text box and whenever the user types something, I want to update the contents of a span. However, I do want to wait for sometime before I update the span. I tried using setTimeout and even setInterval but it doesn't seem to work.

Here is my html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample Title</title>
</head>
<body>
<input type="text" id="text-box-1" />
<span id="results"></span>
</body>
</html>

And my JS:

function update(textValue){
    document.querySelector("#results").innerHTML = textValue;
}

document.querySelector("#text-box-1").onkeyup = function(e){
    setInterval(update(document.querySelector("#text-box-1").value), 5000);
}

When I type in the textbox it starts showing up inside the span instead of waiting for 5 secs. What am I missing here?

Thanks.

Upvotes: 1

Views: 59

Answers (2)

Instant Raptors
Instant Raptors

Reputation: 21

The setInterval() function takes two arguments, a function and a value for timeout. You have given it a statement, which is getting executed immediately and then the setInterval() function does nothing for 5 seconds, because it has not been given a true function to execute.

Simply wrap the statement in an anonymous function to get your desired result. :)

document.querySelector("#text-box-1").onkeyup = function(e){
    setInterval(function(){update(document.querySelector("#text-box-1").value)}, 5000);
}

Hope this helped!

Upvotes: 1

j08691
j08691

Reputation: 207900

You need to wrap your call to your update function in setTimeout within a function.

function update(textValue) {
  document.querySelector("#results").innerHTML = textValue;
}

document.querySelector("#text-box-1").onkeyup = function(e) {
  setInterval(function(){update(document.querySelector("#text-box-1").value)}, 5000);
}
<input type="text" id="text-box-1" />
<span id="results"></span>

Upvotes: 1

Related Questions