Reputation: 1939
In my small Vue application, I'm trying to call the same method (emptyDivision) with different parameters from within another method (buttonClick). I set a 5-second timeout for the first invocation of that method, but this delay is not being recognized when I trigger these two functions by executing buttonClick.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.1/vuex.min.js"></script>
</head>
<body>
<div id="app">
<button v-on:click="buttonClick">Simulate Placement</button>
<h1>Random Division 1</h1>
<p>{{A.One}}</p>
<p>{{A.Two}}</p>
<h1>Random Division 2</h1>
<p>{{B.One}}</P>
<p>{{B.Two}}</p>
</div>
<script type="text/javascript">
new Vue({
'el': '#app',
'data': {
'A': {'One': "", 'Two': "" },
'B': {'One': "", 'Two': "" },
'Division1': ["Steelers", "Ravens"],
'Division2': ["Broncos", "Raiders"],
},
'methods': {
'emptyDivision': function(division){
this.A[division] = this.popTeam(division)[0];
this.B[division] = this.popTeam(division)[0];
},
'popTeam': function(division) {
if (division === "One"){
return this.Division1.splice(Math.floor(Math.random()*this.Division1.length), 1);
}
return this.Division2.splice(Math.floor(Math.random()*this.Division2.length), 1);
},
'buttonClick': function() {
setTimeout(function() {console.log("This appears after 3 seconds")}, 3000);
setTimeout(this.emptyDivision("One"), 5000); /*Teams in division one
("Steelers" and "Ravens") should be propagated to the DOM after 5 seconds, but it's being
evaluated at the same time as the invocation to this.emptyDivision("Two") */
this.emptyDivision("Two"); /* I expect ("Broncos" and "Raiders" to be rendered to the DOM
first due to the timeout, but this is not happening*/
}
}
})
</script>
</body>
</html>
After inspecting the console, the three-second timeout log statement is evaluated and produces the expected behavior, but the five-second timeout to emptyDivision("one") does not appear to be working, as detailed by the comments I left in the above code.
Upvotes: 0
Views: 3894
Reputation: 2181
In the first case you are passing a function definition to setTimeout which will be executed once it is resolved.
In the second case you are directly executing the function, so you need to wrap the statement into a function:
setTimeout( () => this.emptyDivision('one'), 5000)
If emptyDivision returned a function then that function would be executed after the timeout and you wouldn't need to wrap it.
Upvotes: 6